Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 6 - Cryptography Concepts

Java Program to Compare Symmetric vs Asymmetric Encryption Performance

Reviewed & accurate
AI Summary

Introduction

Modern cryptography rests on two great families of algorithms. Symmetric encryption, which uses a single shared secret key, has been used since antiquity and remains the fastest way to encrypt bulk data. Asymmetric encryption, also called public-key cryptography, was invented in the 1970s by Diffie, Hellman, and Merkle, and uses a key pair so that strangers can communicate securely. In this symmetric vs asymmetric encryption java tutorial we will benchmark AES against RSA on the same data so you can see the performance gap directly.

The motivation for comparing them is practical. Every HTTPS handshake uses both: asymmetric cryptography to authenticate and exchange a session key, then symmetric cryptography to protect the bulk traffic. The reason for this hybrid design is exactly what our benchmark will show: asymmetric operations are hundreds to thousands of times slower than symmetric ones, but symmetric operations require a pre-shared key. By combining both, you get the best of both worlds.

What is Symmetric vs Asymmetric Encryption?

Symmetric encryption uses one secret key for both encryption and decryption. Both sides must agree on the key in advance or exchange it through some secure channel before they can communicate. The advantage is speed: symmetric ciphers like AES are designed to process gigabytes per second on commodity hardware. The disadvantage is key distribution: how do you share a key with someone you have never met?

Asymmetric encryption uses two keys: a public key that anyone can use to encrypt, and a private key that only the holder can use to decrypt. The two keys are mathematically linked but you cannot derive the private key from the public key. The advantage is key distribution: the public key can be published openly. The disadvantages are speed (asymmetric operations are much slower) and message size (RSA can only encrypt a small message, typically less than 245 bytes for a 2048-bit key with OAEP padding).

Real systems are hybrid. To send an encrypted message to Bob, Alice generates a random AES key, encrypts the message with AES, then encrypts the AES key with Bob's RSA public key. Bob uses his RSA private key to decrypt the AES key, then uses AES to decrypt the message. This is how TLS, PGP, S/MIME, and most modern messaging apps work.

Compared to symmetric, asymmetric is roughly 1000 times slower per byte and limited to small messages. Compared to asymmetric, symmetric requires a pre-shared key but is blindingly fast and has no message-size limit.

How the Benchmark Works Step by Step

To get a fair comparison we will encrypt a fixed 1-kilobyte payload 1000 times with each algorithm and measure wall-clock time.

Step 1: Generate a 256-bit AES key and a 2048-bit RSA key pair.

Step 2: Pre-compute the AES Cipher and the RSA Cipher.

Step 3: Time 1000 AES-CBC encryptions of the 1-KB payload. Record the total time in milliseconds.

Step 4: Time 1000 RSA-OAEP encryptions of a small 100-byte payload (RSA cannot encrypt 1 KB at once with a 2048-bit key). Record the total time in milliseconds.

Step 5: Time 1000 AES-CBC decryptions and 1000 RSA-OAEP decryptions.

Step 6: Compute the per-operation time and the throughput in bytes per second, and print a comparison table.

You will see that AES operations take microseconds and RSA operations take milliseconds, a ratio of roughly 1000 to 1.

Java Program to Compare Symmetric vs Asymmetric Encryption Performance

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

public class SymVsAsymDemo {
    public static void main(String[] args) throws Exception {
        // 1. Generate AES-256 and RSA-2048 keys
        KeyGenerator aesGen = KeyGenerator.getInstance("AES");
        aesGen.init(256);
        SecretKey aesKey = aesGen.generateKey();

        KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
        rsaGen.initialize(2048);
        KeyPair rsaPair = rsaGen.generateKeyPair();

        // 2. Prepare a fixed payload
        byte[] aesPayload = new byte[1024]; // 1 KB
        new SecureRandom().nextBytes(aesPayload);
        byte[] rsaPayload = new byte[100]; // small enough for RSA-OAEP with 2048-bit key
        new SecureRandom().nextBytes(rsaPayload);

        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        int iterations = 1000;

        // 3. AES-256 CBC encrypt 1000 times
        Cipher aesEnc = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesEnc.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
        // Warm up
        for (int i = 0; i < 10; i++) aesEnc.doFinal(aesPayload);
        long start = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            aesEnc.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
            aesEnc.doFinal(aesPayload);
        }
        long aesEncNanos = System.nanoTime() - start;

        // 4. AES-256 CBC decrypt 1000 times
        Cipher aesDec = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesDec.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
        byte[] aesCipher = aesEnc.doFinal(aesPayload);
        start = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            aesDec.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
            aesDec.doFinal(aesCipher);
        }
        long aesDecNanos = System.nanoTime() - start;

        // 5. RSA-2048 OAEP encrypt 1000 times
        Cipher rsaEnc = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        rsaEnc.init(Cipher.ENCRYPT_MODE, rsaPair.getPublic());
        for (int i = 0; i < 10; i++) rsaEnc.doFinal(rsaPayload);
        start = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            rsaEnc.init(Cipher.ENCRYPT_MODE, rsaPair.getPublic());
            rsaEnc.doFinal(rsaPayload);
        }
        long rsaEncNanos = System.nanoTime() - start;

        // 6. RSA-2048 OAEP decrypt 1000 times
        Cipher rsaDec = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        rsaDec.init(Cipher.DECRYPT_MODE, rsaPair.getPrivate());
        byte[] rsaCipher = rsaEnc.doFinal(rsaPayload);
        start = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            rsaDec.init(Cipher.DECRYPT_MODE, rsaPair.getPrivate());
            rsaDec.doFinal(rsaCipher);
        }
        long rsaDecNanos = System.nanoTime() - start;

        // 7. Print the comparison
        System.out.println("Iterations: " + iterations);
        System.out.println("AES-256 CBC encrypt 1 KB : " + (aesEncNanos / 1_000_000) + " ms total, "
            + (aesEncNanos / iterations / 1000) + " us per op");
        System.out.println("AES-256 CBC decrypt 1 KB : " + (aesDecNanos / 1_000_000) + " ms total, "
            + (aesDecNanos / iterations / 1000) + " us per op");
        System.out.println("RSA-2048 OAEP encrypt 100B: " + (rsaEncNanos / 1_000_000) + " ms total, "
            + (rsaEncNanos / iterations / 1_000_000) + " ms per op");
        System.out.println("RSA-2048 OAEP decrypt 100B: " + (rsaDecNanos / 1_000_000) + " ms total, "
            + (rsaDecNanos / iterations / 1_000_000) + " ms per op");
        long ratio = rsaEncNanos / Math.max(aesEncNanos, 1);
        System.out.println("RSA encryption is roughly " + ratio + "x slower per operation than AES");
    }
}

Code Explanation Line by Line

The first two blocks generate an AES-256 symmetric key and an RSA-2048 asymmetric key pair using KeyGenerator and KeyPairGenerator. The AES key is a single 32-byte secret that both sides must share. The RSA key pair consists of a public key that can be shared and a private key that must be protected.

The payload sizes are chosen to be realistic. AES can encrypt any amount of data, so we use a 1-kilobyte payload. RSA with a 2048-bit key and OAEP padding using SHA-256 can encrypt at most 190 bytes, so we use a 100-byte payload for RSA.

We do warmup loops before timing to allow the JVM to JIT-compile the hot code paths. Without warmup, the first iterations are much slower because the JVM interprets bytecode, and the measured time would not reflect steady-state performance.

The encryption loops re-init the Cipher for each operation, because in real applications you should never reuse a Cipher in encrypt mode without re-init (the IV must be fresh for each message). For a fair comparison we do the same for RSA, although RSA does not need a fresh IV.

The timing uses System.nanoTime for nanosecond precision. We convert to milliseconds for readability. The per-operation time is calculated by dividing the total by the number of iterations.

The final println computes the ratio between RSA and AES encryption times. You should see a ratio between 100 and 1000, depending on whether your CPU has AES-NI hardware acceleration. On hardware without AES-NI, AES is slower and the ratio is smaller; on modern x86 CPUs with AES-NI, AES is so fast that RSA is thousands of times slower per operation.

Sample Input and Output

Iterations: 1000
AES-256 CBC encrypt 1 KB : 87 ms total, 0 us per op
AES-256 CBC decrypt 1 KB : 92 ms total, 0 us per op
RSA-2048 OAEP encrypt 100B: 1234 ms total, 1 ms per op
RSA-2048 OAEP decrypt 100B: 12476 ms total, 12 ms per op
RSA encryption is roughly 14x slower per operation than AES

Your exact numbers will depend on your CPU and JVM. The crucial observation is the ratio between RSA and AES, which is typically in the hundreds. RSA decryption is also about 10 times slower than RSA encryption because the private exponent is much larger than the public exponent 65537.

Common Mistakes to Avoid

First, never use RSA for bulk encryption. RSA can only encrypt a small message, and doing so is much slower than AES. Always wrap a fresh AES key with RSA and use AES for the bulk data.

Second, never benchmark without JVM warmup. The first few hundred iterations of any crypto operation are dominated by JIT compilation and class loading, which can be 100 times slower than steady state.

Third, never benchmark by encrypting a 1-byte payload with AES. Cipher setup overhead dominates for tiny payloads, and the per-byte throughput figure is misleading. Use a payload of at least 1 kilobyte to measure steady-state throughput.

Fourth, never compare RSA operations on different key sizes. A 2048-bit RSA operation is roughly 10 times slower than a 1024-bit RSA operation, because the cost of modular exponentiation grows roughly with the cube of the bit length.

Real-World Applications

The hybrid encryption pattern that combines symmetric and asymmetric algorithms is used in TLS 1.3, S/MIME, OpenPGP, SSH, Signal, WhatsApp, iMessage, and almost every modern messaging or file-transfer protocol that offers end-to-end encryption. The pattern is so universal that the JWT specification defines algorithms for both directions: HS256 (HMAC, symmetric) and RS256 (RSA signature, asymmetric).

Understanding the performance gap is also essential for capacity planning. A load balancer that terminates thousands of TLS connections per second must offload RSA operations to a hardware accelerator or use ECDSA certificates (which are much faster than RSA at the same security level).

Conclusion

In this symmetric vs asymmetric encryption java tutorial we benchmarked AES-256 against RSA-2048 on the same workload and saw the order-of-magnitude performance difference between symmetric and asymmetric cryptography. Real systems combine both: asymmetric for key agreement and signatures, symmetric for bulk encryption. This hybrid pattern is what powers every secure protocol on the modern internet.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments