Master the 5 Most Common Encryption Algorithms in Java

This article introduces the five most widely used encryption algorithms—MD5, SHA‑256, DES, AES, and RSA—explaining their principles, strengths, weaknesses, and providing complete Java code examples for hashing, symmetric, and asymmetric encryption, along with practical usage scenarios such as password storage and HTTPS.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master the 5 Most Common Encryption Algorithms in Java

Hello, I am Su San, a payment developer who frequently works with signing, verification, encryption, and decryption. In this article I review the five most common encryption algorithms.

Preface

In everyday development we often need encryption and decryption, for example:

Storing user passwords as hashed values instead of plain text.

Encrypting sensitive data such as bank card numbers or ID numbers during transmission.

Generating a signature on the client side for payment requests and verifying it on the server side.

Common Encryption Algorithms

Encryption algorithms can be divided into irreversible (hash) algorithms and reversible algorithms . Reversible algorithms are further split into symmetric and asymmetric encryption.

Irreversible Algorithms

Irreversible algorithms produce a hash value that cannot be reversed to the original plaintext. Common hash functions include MD5, SHA‑1, SHA‑224, SHA‑256, etc., and are used for digital signatures, message authentication, and password storage. Some hash‑based algorithms, such as HMAC, also use a secret key.

MD5

MD5 (Message‑Digest Algorithm 5) generates a 128‑bit hash value represented by 32 hexadecimal characters. It is fast but considered insecure due to collision vulnerabilities.

public class MD5 {
    private static final String MD5_ALGORITHM = "MD5";
    public static String encrypt(String data) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(MD5_ALGORITHM);
        byte[] digest = messageDigest.digest(data.getBytes());
        Formatter formatter = new Formatter();
        for (byte b : digest) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }
    public static void main(String[] args) throws Exception {
        String data = "Hello World";
        String encryptedData = encrypt(data);
        System.out.println("Encrypted data: " + encryptedData);
    }
}

MD5 is fast and widely used, but it is vulnerable to brute‑force and rainbow‑table attacks. Adding a salt can mitigate some risks, but SHA family algorithms are preferred.

SHA‑256

The SHA (Secure Hash Algorithm) family, designed by the NSA, includes SHA‑1, SHA‑2, and SHA‑3. SHA‑2 comprises SHA‑224, SHA‑256, SHA‑384, and SHA‑512. SHA‑256 produces a 256‑bit hash and is recommended for security‑critical applications.

public class SHA256 {
    private static final String SHA_256_ALGORITHM = "SHA-256";
    public static String encrypt(String data) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(SHA_256_ALGORITHM);
        byte[] digest = messageDigest.digest(data.getBytes());
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : digest) {
            stringBuilder.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3);
        }
        return stringBuilder.toString();
    }
    public static void main(String[] args) throws Exception {
        String data = "Hello World";
        String encryptedData = encrypt(data);
        System.out.println("Encrypted data: " + encryptedData);
    }
}

SHA‑2 offers longer hash values and stronger collision resistance compared to MD5, but salting remains essential to protect against brute‑force attacks.

Symmetric Encryption Algorithms

Symmetric algorithms use the same secret key for encryption and decryption, making key management critical. Common symmetric algorithms include DES, 3DES, and AES, with AES being the most widely adopted due to its security and performance.

DES

DES (Data Encryption Standard) is an older symmetric algorithm that uses a 56‑bit key. It is fast but insecure against modern attacks.

public class DES {
    private static final String DES_ALGORITHM = "DES";
    /**
     * DES encryption
     * @param data Data to encrypt
     * @param key 8‑byte key
     * @return Base64‑encoded ciphertext
     */
    public static String encrypt(String data, String key) throws Exception {
        KeySpec keySpec = new DESKeySpec(key.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
        SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(DES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    /**
     * DES decryption
     * @param encryptedData Base64‑encoded ciphertext
     * @param key 8‑byte key
     * @return Decrypted plaintext
     */
    public static String decrypt(String encryptedData, String key) throws Exception {
        KeySpec keySpec = new DESKeySpec(key.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
        SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        Cipher cipher = Cipher.getInstance(DES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData);
    }
    public static void main(String[] args) throws Exception {
        String data = "Hello World";
        String key = "12345678";
        String encryptedData = encrypt(data, key);
        System.out.println("Encrypted data: " + encryptedData);
        String decryptedData = decrypt(encryptedData, key);
        System.out.println("Decrypted data: " + decryptedData);
    }
}

DES is fast but its short key makes it vulnerable to brute‑force and differential attacks; 3DES or AES are recommended instead.

AES

AES (Advanced Encryption Standard) supports 128‑, 192‑, and 256‑bit keys and is the current standard for symmetric encryption.

public class AES {
    private static final String AES_ALGORITHM = "AES";
    private static final String AES_TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String AES_KEY = "1234567890123456"; // 16‑byte key
    private static final String AES_IV = "abcdefghijklmnop"; // 16‑byte IV
    /**
     * AES encryption
     * @param data Plaintext
     * @return Base64‑encoded ciphertext
     */
    public static String encrypt(String data) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes());
        Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    /**
     * AES decryption
     * @param encryptedData Base64‑encoded ciphertext
     * @return Decrypted plaintext
     */
    public static String decrypt(String encryptedData) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes());
        Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }
    public static void main(String[] args) throws Exception {
        String data = "Hello World";
        String encryptedData = encrypt(data);
        System.out.println("Encrypted data: " + encryptedData);
        String decryptedData = decrypt(encryptedData);
        System.out.println("Decrypted data: " + decryptedData);
    }
}

AES provides a larger key space and stronger resistance to brute‑force attacks, making it suitable for most modern applications.

Asymmetric Encryption Algorithms

Asymmetric algorithms use a key pair: a public key for encryption and a private key for decryption. They are essential for key exchange, digital signatures, and establishing secure channels.

RSA

RSA, invented in 1978 by Rivest, Shamir, and Adleman, is the most widely used public‑key algorithm.

public class RSA {
    private static final String RSA_ALGORITHM = "RSA";
    /** Generate RSA key pair */
    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }
    /** Encrypt with public key */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    /** Decrypt with private key */
    public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }
    public static void main(String[] args) throws Exception {
        KeyPair keyPair = generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        String data = "Hello World";
        String encryptedData = encrypt(data, publicKey);
        System.out.println("Encrypted data: " + encryptedData);
        String decryptedData = decrypt(encryptedData, privateKey);
        System.out.println("Decrypted data: " + decryptedData);
    }
}

RSA offers high security, but encryption and decryption are slower than symmetric algorithms, and key length must be chosen carefully to balance security and performance.

Summary

This article covered the five most common encryption algorithms—MD5, SHA‑256, DES, AES, and RSA—detailing their mechanisms, advantages, drawbacks, and providing ready‑to‑run Java implementations.

In practice, protocols like HTTPS combine these algorithms: asymmetric encryption (RSA) to exchange a symmetric key, symmetric encryption (AES) for bulk data transfer, and hash functions (SHA‑256) for integrity verification.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

encryptionHashingasymmetricsymmetric
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.