Module 32: Java SecurityBeginner22 min read
Secure Coding, Hashing & Cryptography in Java
Protect Java applications against injection, weak randomness, and insecure data storage using MessageDigest and SecureRandom.
Key Takeaways & Core Concepts
- Protect Java applications against injection, weak randomness, and insecure data storage using MessageDigest and SecureRandom.
- Practice writing and running standard examples.
- Apply best practices and debugging techniques.
Secure Coding, Hashing & Cryptography in Java
### Secure Coding Principles in Java Security is a core architectural concern, not an afterthought:
- 1Input Validation & Allow-Listing: Validate length, type, and regex format at API boundaries before data reaches business logic or SQL.
- 2SQL Injection Prevention: Always use parameterized
PreparedStatementor JPA bind parameters. - 3Password Hashing: Never store plain-text passwords or fast unsalted SHA-256 digests (GPUs can brute-force billions of SHA-256 hashes per second). Always use salted, memory-hard adaptive hashing (Argon2id, BCrypt, or PBKDF2WithHmacSHA256).
- 4Cryptographic Randomness: Always use
SecureRandomfor session IDs, CSRF tokens, and salts. - 5Constant-Time Comparisons: Use
MessageDigest.isEqual(a, b)when comparing HMAC signatures or tokens to prevent timing side-channel attacks.
SHA-256 Digest with MessageDigest
1import java.nio.charset.StandardCharsets;
2import java.security.MessageDigest;
3
4public class Main {
5 public static void main(String[] args) throws Exception {
6 MessageDigest md = MessageDigest.getInstance("SHA-256");
7 byte[] hash = md.digest("CodeZov".getBytes(StandardCharsets.UTF_8));
8 StringBuilder hex = new StringBuilder();
9 for (byte b : hash) hex.append(String.format("%02x", b));
10 System.out.println("SHA-256 length: " + hex.length() + " hex chars");
11 }
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: SHA-256 produces a fixed 256-bit (64 hex character) cryptographic digest.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)