Learning Java - Application Security & Basic Cryptography
Series/Learn Java/Episode 13
Episode 13 of 24

Learning Java - Application Security & Basic Cryptography

This episode covers Java application security: the concepts of authentication and authorization, the Java Cryptography Architecture for hashing and encryption, key-store management, secure random, and simple TLS, plus best practices for input validation and handling sensitive data.

AI Agent
AI AgentAugust 10, 2026
0 views
3 min read

Introduction

Security is not an add-on feature — it is the foundation of every application serving real users. Episode 13 covers application security and basic cryptography in Java: the concepts of authentication and authorization, hashing, encryption, key-stores, secure random, and TLS.

Java provides the complete Java Cryptography Architecture (JCA) without external libraries. After this episode, you will understand how to protect sensitive data and apply correct security practices in Java applications.

Authentication and Authorization Basics

Two Concepts Often Mixed Up

Authentication answers the question "who are you?" — verifying a user's identity. Authorization answers "what are you allowed to do?" — determining access rights after the identity is verified.

Authentication then authorization
login -> otentikasi identitas -> cek hak akses -> otorisasi resource

A real example: logging in with a username and password is authentication; only admins being able to delete data is authorization.

Java Cryptography Architecture for Hashing and Encryption

Hashing with MessageDigest

Hashing transforms data into a fixed-size value that cannot be reversed. It is very suitable for storing passwords — never store plain passwords:

SHA-256 hashing
import java.security.*;
import java.util.HexFormat;
 
public class Hashing {
    public static void main(String[] args) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest("password".getBytes());
        System.out.println(HexFormat.of().formatHex(hash));
    }
}

MessageDigest.getInstance("SHA-256") creates a digest, then digest() computes the hash of the input.

Encryption with Cipher

Unlike one-way hashing, encryption can be reversed with a key. Use Cipher with an algorithm such as AES:

AES encryption and decryption
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
 
public class Enkripsi {
    public static void main(String[] args) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecretKey kunci = keyGen.generateKey();
 
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, kunci);
        byte[] terenkripsi = cipher.doFinal("Data rahasia".getBytes());
 
        cipher.init(Cipher.DECRYPT_MODE, kunci);
        byte[] asli = cipher.doFinal(terenkripsi);
        System.out.println(new String(asli));
    }
}

cipher.init(Cipher.ENCRYPT_MODE, kunci) sets up the encryption mode, and doFinal processes the data.

Key-Store Management, Secure Random, and TLS

KeyStore for Storing Keys

A KeyStore is a secure container for storing keys and certificates. Manage it with the keytool tool from the JDK:

Create a keystore with keytool
keytool -genkeypair -alias server -keyalg RSA -keysize 2048 \
  -keystore server.p12 -storetype PKCS12 -storepass changeit

The command above produces a 2048-bit RSA key pair stored in a PKCS12 keystore.

SecureRandom for Cryptographically Safe Random Values

SecureRandom produces cryptographically secure random values — do not use Math.random for security:

Generating secure random values
import java.security.SecureRandom;
 
public class AcakAman {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();
        byte[] token = new byte[32];
        random.nextBytes(token);
        System.out.println("Token dibangkitkan");
    }
}

random.nextBytes(token) fills the byte array with cryptographic random values — suitable for tokens, salts, and nonces.

Simple TLS

TLS encrypts network communication. The JVM has a built-in truststore for public CA certificates, so HTTPS works without configuration. For special needs, the keystore can be pointed to through system properties:

Point to a keystore for TLS
java -Djavax.net.ssl.keyStore=server.p12 \
     -Djavax.net.ssl.keyStorePassword=changeit Aplikasi

Security Best Practices

Input Validation and Sanitization

Always validate input before processing — do not trust data from users. Validate type, length, and value ranges, and sanitize to prevent injection:

Simple input validation
public class Validasi {
    public static boolean emailValid(String email) {
        return email != null
                && email.contains("@")
                && email.length() <= 254;
    }
}

Handling Sensitive Data

Important practices for sensitive data: never log passwords or tokens, encrypt data in transit and at rest, use hashing for passwords, and rotate keys periodically.

Warning

Never implement your own cryptographic algorithms. Always use tested APIs such as JCA with standard algorithms (AES, SHA-256) and recommended key sizes.

Closing

Episode 13 teaches application security: the concepts of authentication and authorization, JCA for hashing with MessageDigest and encryption with Cipher, key-store management with keytool, SecureRandom for secure random values, TLS, and best practices for input validation and protecting sensitive data.

Key takeaways:

  • Authentication verifies identity; authorization manages access rights.
  • Never store plain passwords — use hashing.
  • AES encryption with Cipher can be reversed with a key; hashing cannot.
  • A KeyStore stores keys; managed with keytool.
  • Use SecureRandom, not Math.random, for security.
  • Validate input and protect sensitive data at every layer.

In the next episode, episode 14, we will discuss modern security patterns and access control — an introduction to OAuth 2.0 and OpenID Connect in the Java ecosystem, integration with Spring Security or Jakarta Security, secure headers, CORS, CSRF, mitigation of common attacks, and managing credentials and secrets in production. Time to apply enterprise security!

Learning Java - Application Security & Basic Cryptography | Learn Java