Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 201 ยท Working with Data

UUIDs, Hashing and Base64

Create UUIDs in Java, hash data with MessageDigest and SHA-256, print bytes with HexFormat, encode with Base64, verify with HMAC and compute CRC32 checksums.

Programs constantly need to turn data into other data with special properties. An order needs an ID that's unique across every server without asking a central database. A downloaded file needs a fingerprint to prove it wasn't corrupted or tampered with. A binary key needs to travel inside JSON or a URL, which only accept text. Java's standard library covers all of these: UUID for unique identifiers, MessageDigest and Mac for cryptographic hashes, HexFormat and Base64 for turning bytes into printable text, and CRC32 for fast checksums.

These tools are often confused with each other, and the confusion causes real security bugs (Base64 "encryption", SHA-256 "password storage"). This lesson explains what each one guarantees, what it doesn't, and shows the correct code for the common jobs.

UUIDs: unique IDs without coordination

A UUID (universally unique identifier) is a 128-bit value, usually written as 32 hex digits in five groups: 8-4-4-4-12. Java's java.util.UUID class creates, parses and compares them:

Java Creating and inspecting UUIDs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Key facts:

  • UUID.randomUUID() creates a version 4 UUID: 122 random bits from a SecureRandom, plus 6 fixed bits that mark the version and variant. The chance of two ever colliding is so small that you can treat them as unique, even across millions of machines.
  • UUID.nameUUIDFromBytes(bytes) creates a version 3 UUID by hashing the bytes with MD5. The same input always gives the same UUID, which is useful for turning an existing natural key into a stable ID. (Version 5 uses SHA-1 instead; the JDK doesn't provide it, but libraries do.)
  • UUID is a value type: equals, hashCode and compareTo work, so UUIDs are fine as map keys. toString() always prints lowercase; fromString accepts either case.
  • In a database, store UUIDs in a native UUID or 16-byte binary column rather than a 36-character string when you can: it's less than half the size.

Time-ordered UUIDs (version 7)

Random v4 UUIDs have one drawback as database primary keys: new rows land at random places in the index, which slows inserts on large tables. Version 7 UUIDs (standardized in RFC 9562, 2024) start with a 48-bit millisecond timestamp, so they sort roughly by creation time while staying unique. The JDK has no factory for them as of Java 25, but because the layout is simple, you can build one from the two 64-bit halves:

Java Building a version 7 UUID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first 12 hex digits are the timestamp, so the IDs sort as text in the order they were made. In real code you'd call uuidV7(System.currentTimeMillis()), and a production generator also guarantees ordering for several IDs created in the same millisecond. Bit masks like 0x0FFFL are explained in Bitwise and Shift Operators.

Cryptographic hashes with MessageDigest

A hash function turns input of any length into a fixed-size output called a digest. A cryptographic hash like SHA-256 adds strong guarantees:

  • Deterministic: the same input always gives the same digest.
  • Avalanche effect: changing one bit of input changes about half the output bits.
  • One-way: you can't reconstruct the input from the digest.
  • Collision-resistant: nobody can find two different inputs with the same digest.

java.security.MessageDigest computes these. The digest is a byte[]; to print it, use HexFormat (Java 17):

Java SHA-256 digests and the avalanche effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Changing a single letter produces a completely different digest. You can check the first line yourself: SHA-256 of hello (encoded as UTF-8) is 2cf24dba...9824 in every language and tool, which is exactly what makes digests useful for verifying downloads.

Things to know about MessageDigest:

  • Always convert text to bytes with an explicit charset (StandardCharsets.UTF_8); otherwise the same string can hash differently on different systems. See Character Sets and Encoding.
  • getInstance throws the checked NoSuchAlgorithmException for unknown names. Every JDK must support SHA-256, so it never actually happens for that name.
  • For large data, call update(chunk) repeatedly and then digest() once, instead of loading everything into memory. A MessageDigest object isn't thread-safe; create one per use (it's cheap).
  • MD5 and SHA-1 are broken for security: attackers can create collisions. They're acceptable only for non-security uses like cache keys. Use SHA-256 or stronger for anything that matters.
  • To compare two digests, use MessageDigest.isEqual(a, b). It takes the same time no matter where the arrays differ, so it doesn't leak information through timing the way an early-exit comparison can.

HexFormat: bytes as readable hex

HexFormat (Java 17) replaced the hand-written hex loops found in older code. It formats, parses and customizes:

Java HexFormat for printing and parsing bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice [-54, -2, -70, -66]: Java's byte is signed, so values above 0x7F print as negative numbers. The bits are the same; only the decimal interpretation differs, which is one more reason to look at bytes in hex.

Base64: binary data as text

Many formats only carry text: JSON, XML, email, URLs, HTTP headers. Base64 encodes any bytes using 64 safe characters (Aโ€“Z, aโ€“z, 0โ€“9 and two more), producing 4 characters for every 3 bytes. java.util.Base64 has three flavors:

Java Basic, URL-safe and MIME Base64

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Basic (getEncoder) uses + and /. Those characters have special meanings in URLs and file names.
  • URL-safe (getUrlEncoder) uses - and _ instead, so the text can go in a URL or file name unchanged. withoutPadding() drops the trailing = signs, as JSON Web Tokens do. The decoder accepts both padded and unpadded input.
  • MIME (getMimeEncoder) breaks lines at 76 characters with \r\n, as email attachments need; its decoder ignores line breaks and other non-Base64 characters.
  • Invalid input throws IllegalArgumentException; in the demo, character 20 is the hex code of the first space.
  • The output is about 33% larger than the input. Base64 is for transport, not storage efficiency.

Base64 is not encryption. Anyone can decode it instantly. Encoding a password or API key in Base64 hides nothing. If data must be secret, encrypt it; if it must be unforgeable, sign it with an HMAC (below).

HMAC: hashes with a secret key

A plain hash proves data wasn't corrupted, but not that it came from you: an attacker who changes the data can just recompute the hash. An HMAC (hash-based message authentication code) mixes a secret key into the hash, so only someone who knows the key can produce a valid tag. Web APIs use HMACs to sign webhooks, cookies and download links:

Java Signing and verifying with HmacSHA256

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Changing the file name invalidates the signature, and without the key an attacker can't compute a new one. Real keys come from configuration or a secrets manager, never from source code, and should be at least 32 random bytes (generated with SecureRandom, as in Random Numbers).

What about passwords?

Never store passwords as plain SHA-256 hashes. SHA-256 is designed to be fast, so an attacker with a stolen database can test billions of guesses per second. Password hashing needs a deliberately slow, salted algorithm: bcrypt, scrypt or Argon2 (from libraries such as Spring Security), or PBKDF2, which the JDK includes:

Java
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);                  // unique per user, stored with the hash

var spec = new PBEKeySpec(password, salt, 600_000, 256);   // char[] password, iterations, bits
byte[] hash = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
        .generateSecret(spec).getEncoded();

The salt makes identical passwords hash differently, and the iteration count makes every guess expensive. Store the algorithm, iteration count, salt and hash together so you can raise the cost later. Authentication frameworks in Advanced Java handle this for you; prefer them over hand-rolled code.

Checksums: CRC32 and friends

Sometimes you only need to detect accidental corruption: a flipped bit on disk, a truncated download, a damaged ZIP entry. Cryptographic hashes work, but a checksum is much faster. java.util.zip provides CRC32, CRC32C (Java 9, hardware-accelerated on modern CPUs) and Adler32, all implementing the Checksum interface:

Java Detecting corruption with CRC32

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A single flipped bit turned 1,250.00 into 1,650.00, and the CRC changed completely. CRC32 values are 32 bits, returned in a long so they're never negative. Because CRCs are easy to forge on purpose, use them only against accidents; against attackers, use SHA-256 or an HMAC. You'll meet CRC32 again in Compressing Data with GZIP and ZIP, since every ZIP entry stores one.

Choosing the right tool

You need Use Not
A unique ID UUID.randomUUID() (or v7 for sortable keys) a hash of the current time
To detect accidental corruption CRC32C / CRC32 nothing at all
A fingerprint attackers can't fake a collision for MessageDigest with SHA-256 MD5, SHA-1
Proof a message came from someone with the key Mac with HmacSHA256 a plain hash
To store passwords bcrypt / Argon2 / PBKDF2 with a salt SHA-256, Base64
Binary data in text formats Base64 (URL-safe for URLs) treating bytes as a String
Bytes readable by humans HexFormat hand-written hex loops

Remember that hashCode() is a different thing again: a fast 32-bit value for HashMap buckets, with collisions expected and no security at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does UUID.nameUUIDFromBytes("order-17".getBytes()) return when called twice?

    nameUUIDFromBytes creates a version 3 UUID by hashing the bytes with MD5, so equal input always gives an equal UUID.
  2. 2. Your API stores user passwords. Which approach is correct?

    Base64 is reversible, and SHA-256 is too fast to resist guessing. Password hashing needs a per-user salt and a deliberately expensive algorithm.
  3. 3. Why would you choose Base64.getUrlEncoder() over getEncoder()?

    The URL-safe alphabet avoids characters that have special meanings in URLs and paths. Output length is the same, and neither flavor encrypts anything.
  4. 4. A webhook sender includes a SHA-256 hash of the body. Why isn't that enough to prove the request is genuine?

    Anyone can compute a plain hash. An HMAC mixes in a secret key, so only key holders can produce a valid tag.
  5. 5. What does HexFormat.of().formatHex(new byte[]{ (byte) 0xFF, 0x0A }) return?

    HexFormat.of() prints two lowercase hex digits per byte with no delimiter. Uppercase and delimiters must be requested with withUpperCase() and ofDelimiter().

Summary

  • UUID.randomUUID() gives a random version 4 ID; nameUUIDFromBytes gives a stable version 3 ID from input; time-ordered version 7 IDs can be built with new UUID(msb, lsb).
  • MessageDigest.getInstance("SHA-256") produces fixed-size, one-way, collision-resistant digests. Encode text with an explicit charset, avoid MD5/SHA-1 for security, and compare with MessageDigest.isEqual.
  • HexFormat (Java 17) formats and parses hex, with optional delimiters, prefixes and uppercase.
  • Base64 encodes bytes as text: basic, URL-safe (often without padding) or MIME. It's an encoding, not encryption.
  • Mac with HmacSHA256 signs messages with a secret key; passwords need bcrypt, Argon2 or PBKDF2 with a salt.
  • CRC32/CRC32C detect accidental corruption quickly but offer no protection against attackers.

Next: Locales and Internationalization, where you'll format numbers, currencies and dates the way people in each country expect.