Quick revision
The short answer
We fill a 32-byte array with SecureRandom, then encode it with Base64.getUrlEncoder().withoutPadding(), which uses - and _ instead of + and / and drops the = padding, so the 43-character token can go into a URL path or query without escaping. Base64.getUrlDecoder().decode(token) turns it back into the same 32 bytes and accepts the missing padding. The basic decoder rejects line breaks, while getMimeDecoder() tolerates them for PEM and email, and invalid input throws IllegalArgumentException, which we treat as a client error.
What to remember
In this answer, we generated a 32-byte token with SecureRandom and encoded it with Base64.getUrlEncoder().withoutPadding(), which uses - and _ instead of + and / and drops the padding, so the 43-character result is safe in URLs. Base64.getUrlDecoder() decodes it back and accepts the missing padding. We saw that the MIME decoder tolerates line breaks used in PEM and email while the basic decoder rejects them, and that invalid input throws IllegalArgumentException, which we answer as a client error.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We fill a 32-byte array with SecureRandom, then encode it with Base64.getUrlEncoder().withoutPadding(), which uses - and _ instead of + and / and drops the = padding, so the 43-character token can go into a URL path or query without escaping. Base64.getUrlDecoder().decode(token) turns it back into the same 32 bytes and accepts the missing padding. The basic decoder rejects line breaks, while getMimeDecoder() tolerates them for PEM and email, and invalid input throws IllegalArgumentException, which we treat as a client error.
Why this question is asked
Random tokens are everywhere in web applications: password reset links, email verification links, invitation codes, API keys. They are generated as bytes, but they have to travel as text, often inside a URL. Choosing the wrong Base64 variant produces tokens that break in some links and not others, which is a classic intermittent bug. Interviewers ask this small coding question to see whether we know the variants in java.util.Base64 and why the URL-safe one exists. In this answer, we will generate the token, compare the standard and URL-safe encoders, decode it back, look at the MIME decoder, and handle invalid input properly.
1Generating the 32 Random Bytes
A token must be unpredictable, so we use SecureRandom, never java.util.Random. 32 bytes gives 256 bits of randomness, far beyond what anyone can guess. new SecureRandom() is the right default on modern JDKs; SecureRandom.getInstanceStrong() selects the strongest configured algorithm but can block on some systems while waiting for entropy, so it is better kept for long-term keys than for tokens generated on every request.
2Why the Standard Encoder Is Wrong for URLs
The standard Base64 alphabet includes +, / and the = padding character. All three have special meanings in URLs. A / splits path segments. A + in a query string is decoded as a space by most servers, including the servlet getParameter method. An = separates a parameter name from its value. So a standard Base64 token can be silently changed on its way through a link.
Notice that this only happens for some tokens. Each character has a 1 in 64 chance of being +, and another 1 in 64 of being /, so with 43 characters a large share of tokens contain at least one of them, but not all. That is why the bug often appears as "some reset links do not work".
| Factory | Alphabet ends with | Padding | Line breaks |
|---|---|---|---|
getEncoder / getDecoder | + and / | = added; decoder accepts it | rejected by decoder |
getUrlEncoder / getUrlDecoder | - and _ | = unless withoutPadding() | rejected by decoder |
getMimeEncoder / getMimeDecoder | + and / | = added | encoder adds every 76 chars, decoder ignores |
3Encoding With the URL-Safe Encoder Without Padding
The URL-safe variant, defined in RFC 4648 as base64url, replaces + with - and / with _, two characters that have no special meaning in URLs. withoutPadding() drops the trailing =, which carries no information because the decoder can work out the length. The result for 32 bytes is always 43 characters.
This is the same encoding used for JWT segments, which is another reason it is the natural choice for tokens on the web.
4Decoding It Back
The URL decoder reverses the process. It accepts input with or without padding, so a token produced by withoutPadding() decodes without any extra work. We compare the decoded bytes, or better, a hash of the token stored in the database, rather than comparing strings that might differ in padding.
5The MIME Decoder and Line Breaks
PEM files (certificates, keys) and email bodies wrap Base64 text into lines of 64 or 76 characters. The basic and URL decoders reject any character outside their alphabet, including line breaks, so decoding a PEM body with getDecoder() fails. getMimeDecoder() ignores characters outside the alphabet, including CR and LF, so it is the right tool for those formats. We should not use it for tokens, because silently ignoring junk is the opposite of what we want for input from a URL.
6Handling Invalid Input as a Client Error
A token in a URL comes from the outside world, so it may be truncated by an email client, mistyped or deliberately malformed. Decoding invalid input throws IllegalArgumentException. In a Spring controller we catch it, or validate first, and respond with 400 Bad Request or the same "link invalid or expired" page as for an unknown token, never with a 500 and a stack trace.
Notice the length check. A string can decode cleanly but to the wrong number of bytes, so we check for exactly 32 before using it.
7Follow-up questions
Could we just URL-encode a standard Base64 token instead?
Yes, URLEncoder.encode turns + into %2B, / into %2F and = into %3D, and that works. But every place that builds or reads the link must remember to encode and decode correctly, and the token becomes longer and uglier. URL-safe Base64 avoids the problem at the source.
Why not use hex encoding for the token?
Hex is also URL-safe and simple, but it doubles the size: 32 bytes become 64 characters instead of 43. It is a fine choice when length does not matter; Base64url is more compact.
8Conclusion
In this answer, we generated a 32-byte token with SecureRandom and encoded it with Base64.getUrlEncoder().withoutPadding(), which uses - and _ instead of + and / and drops the padding, so the 43-character result is safe in URLs. Base64.getUrlDecoder() decodes it back and accepts the missing padding. We saw that the MIME decoder tolerates line breaks used in PEM and email while the basic decoder rejects them, and that invalid input throws IllegalArgumentException, which we answer as a client error.
Open with
I would create a byte array of 32, fill it with a shared SecureRandom instance, which gives 256 bits, and encode it with Base64.getUrlEncoder().withoutPadding().encodeToString. I choose the URL-safe variant because standard Base64 uses plus, slash and equals, and all three mean something in a URL: a plus in a query string becomes a space, a slash splits a path, and equals separates names from values.
Then, if they want more
Only some tokens contain those characters, so the bug shows up as some links failing. The URL alphabet uses minus and underscore instead, and without padding a 32-byte token is always 43 characters that can be put in a link as they are. It is also what JWTs use.
To decode, I call Base64.getUrlDecoder().decode, which accepts the missing padding, and I check that I get exactly 32 bytes back. If the input is invalid, the decoder throws IllegalArgumentException, and since the token comes from a user, I treat that as a 400 or the same invalid-link page as an unknown token, not a 500.
I would also mention the MIME decoder: PEM files and email wrap Base64 in lines, and the basic decoder rejects line breaks, while getMimeDecoder ignores them, but I would not use it for tokens because it silently skips junk. And I would store only a hash of the token in the database.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Security reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Encode a 32-byte random token for use in a URL and decode it back in Java. Which Base64...": https://scrivio-interview-library.netlify.app/spring-boot/secrets-and-crypto/e1d1f0dc2f/