Standard libraries

libs3CryptoAndHashing

Path
pkg13libs/libs3CryptoAndHashing.java
Package
pkg13libs
Study order
3
Run
Single-file source launch
Command
java pkg13libs/libs3CryptoAndHashing.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg13libs/libs3CryptoAndHashing.java
1package pkg13libs;2 3import java.nio.charset.StandardCharsets;4import java.security.MessageDigest;5import java.security.NoSuchAlgorithmException;6import java.security.SecureRandom;7import java.util.Base64;8import javax.crypto.Mac;9import javax.crypto.spec.SecretKeySpec;10 11/*12 * libs3CryptoAndHashing.java13 * --------------------------14 * Hashing, HMAC, and Base64 with the built-in java.security / javax.crypto APIs.15 *16 * DEFINITION:17 *   A cryptographic hash (SHA-256) maps data to a fixed-size digest (one-way).18 *   HMAC adds a secret key for authenticity. Base64 encodes bytes as ASCII text19 *   (encoding, NOT encryption).20 *21 * KEY POINTS:22 *   - MessageDigest computes hashes (SHA-256 preferred; avoid MD5/SHA-1).23 *   - For passwords use a slow KDF (PBKDF2/bcrypt/Argon2), NOT a plain hash.24 *   - HMAC proves a message came from someone who holds the key.25 *   - Base64.getEncoder()/getDecoder() is the standard text-safe byte transport.26 */27public class libs3CryptoAndHashing {28 29    public static void main(String[] args) throws Exception {30        String message = "the quick brown fox";31 32        // 1) SHA-256 hash33        byte[] digest = sha256(message);34        System.out.println("SHA-256 (hex)   : " + toHex(digest));35        System.out.println("SHA-256 (base64): " + Base64.getEncoder().encodeToString(digest));36 37        // Same input -> same hash; tiny change -> totally different hash38        System.out.println("\nDeterministic?  : " + (toHex(sha256(message)).equals(toHex(digest))));39        System.out.println("Avalanche       : " + toHex(sha256(message + "!")).substring(0, 16) + "...");40 41        // 2) Base64 round-trip42        String encoded = Base64.getEncoder().encodeToString(message.getBytes(StandardCharsets.UTF_8));43        String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);44        System.out.println("\nBase64 encoded  : " + encoded);45        System.out.println("Base64 decoded  : " + decoded);46 47        // 3) HMAC-SHA256 (keyed authentication)48        Mac mac = Mac.getInstance("HmacSHA256");49        mac.init(new SecretKeySpec("super-secret-key".getBytes(StandardCharsets.UTF_8), "HmacSHA256"));50        byte[] tag = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));51        System.out.println("\nHMAC-SHA256     : " + toHex(tag));52 53        // 4) Cryptographically strong random bytes (e.g. tokens, salts)54        byte[] salt = new byte[16];55        SecureRandom.getInstanceStrong().nextBytes(salt);56        System.out.println("Random salt     : " + Base64.getEncoder().encodeToString(salt));57    }58 59    static byte[] sha256(String s) throws NoSuchAlgorithmException {60        return MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8));61    }62 63    static String toHex(byte[] bytes) {64        StringBuilder sb = new StringBuilder(bytes.length * 2);65        for (byte b : bytes) sb.append(String.format("%02x", b));66        return sb.toString();67    }68}