Java4Shell. Who’s laughing at PHP now?
I remember when Calif disclosed PHP2Shell. I laughed. Back at Amazon we had internal wikis enumerating in exacting technical detail why you should never use PHP. After having to use Drupal for a website redesign at ASU, I thought they were being kind. Drupal even made Calif’s list.
Then I read Java4Shell.
Ruh roh, Raggy.

On an affected JVM, decoding Base64 from the wrong stranger can give them remote code execution in production. Calif demonstrated it against Jenkins, among others. Patch your JDK. The WebSocket code in Kompuwiz uses our own Base64 decoder, so that particular call never goes near the busted one.
I’ve been trying to get off of Java and onto the holy land of Clojure/Rust/Lisp for years. But I read Bloch, Lea, Goetz, and basically all the “how to do Java right” books and finally got myself to kinda sorta doing Java mostly right. It always felt like a huge productivity suck to give that up. I can fly around in Python any time I want, but it’s rather slow and easy to build code that doesn’t do what you want for being one space too indented. TypeScript reminds me of C++11, finding new ways to hammer complexity onto what Crockford called “The Good Parts.” I still think a generic type system where the generics themselves are Turing complete is a little “anything you can do I can do meta” for its own good.
So I stuck with old reliable. Which makes this vulnerability hurt.
Still, I’ve had a feeling I eventually had to get away from Java, so I’ve been building Kompuwiz the way Kotlin started out: hosted on the platform, with ideas of getting off. This has led me to the point of madness.
I remember one of my best friends telling me, in a hot tub, “You can’t rebuild the world, Nico.”

Meanwhile, in my head:

But why should the world be rebuilt?
When I was in undergrad, I took CSE421: Microprocessor Design. It was widely acknowledged to be the hardest course in our school. We had to read the DragonBall MX 68000 board programming manual and bend it to our will. We had to debounce buttons, draw on the LCD, implement the timers on the board and wire up the interrupt tables. I spent weekends, weekends when college kids were supposed to be drinking and fooling around, in the lab with that board. Becoming one with the machine. When we were told to integrate with just one timer in the manual, I figured out the general pattern and integrated with the special-purpose timer that was part of the assignment and the general timer, just for fun. THIS is what a nerd does when he doesn’t know how to get a date.
With all the complexity of writing C code to interface directly with interrupt tables, things like string concatenation were considered “distracting from the main goal.” We couldn’t use the STL, so the class gave us string manipulation libraries written by TAs.
The libraries had bugs.
Several of us spent an entire weekend trying to figure out why we couldn’t draw the strings we expected on our screens. Multiple students, all writing test cases and trying things, sure our own code was at fault. Finally we realized the library was calculating the offsets wrong.
Most people patched around the bug. I looked at the rest of the library. It was about 250 KB and I was using maybe 4 KB of it. So I threw it out and wrote my own little string library that did just the handful of things my controller needed.
My final project was a vending machine controller. Writing those string routines myself saved me enough room to put rich images and cute animations on the LCD, just to fuck around. With the animations in it, my controller was still smaller and more efficient than half the class’s.
That experience taught me that any time you’re given free code, there are always two important questions:
- Does it actually do what it says on the can?
- Do you really need all that?
Most people think “it doesn’t really matter” and just keep bundling crap on crap on crap until they have a wobbly Jenga tower of tech debt and one little gust of wind creates a giant problem.
I have this irrational and insane idealism that efficient, minimal, well-designed software will win in the end. Most of the time I’m probably wrong, judging by VC standards. But every once in a while I get to have a moment to cackle with glee.
“You’re crazy to rebuild your own standard library and framework,” they said.
But in the age of AI, if you’re not doing it, are you sure it’s not just because you don’t know how?
We’re all trying to solve Big Tough Problems. I chose to work my way up by solving little problems, trying to make them correct by construction. Like Base64.
How Java PHPed itself
Base64 is read four characters at a time, three bytes to a group. Here’s where that comes from.
It’s three pixels by three, greyscale, a byte to a pixel. 00 is black and FF is white, so the whole picture is nine bytes:

Headers and email bodies only carry text, so Base64 spells bytes out of 64 characters that survive the trip. Sixty-four choices is six bits’ worth, so it cuts the same bits six at a time. Three bytes are 24 bits, which is four characters exactly:

Why is 000000 an A? Each six bits pick a character out of this table. The first three bits pick the row, the last three the column:
| 000 | 001 | 010 | 011 | 100 | 101 | 110 | 111 | |
|---|---|---|---|---|---|---|---|---|
| 000 | A | B | C | D | E | F | G | H |
| 001 | I | J | K | L | M | N | O | P |
| 010 | Q | R | S | T | U | V | W | X |
| 011 | Y | Z | a | b | c | d | e | f |
| 100 | g | h | i | j | k | l | m | n |
| 101 | o | p | q | r | s | t | u | v |
| 110 | w | x | y | z | 0 | 1 | 2 | 3 |
| 111 | 4 | 5 | 6 | 7 | 8 | 9 | + | / |
All 64 squares are taken, and = isn’t in one of them. It carries no bits. It’s filler for when the bytes run out partway through a group, and the bytes can only run out once, at the end:

So only the last group may run short, and RFC 4648 gives it exactly three shapes. Calif’s input ends in a fourth.
| The text ends in | RFC 4648 | Java sees | Mine builds |
|---|---|---|---|
AAAA | three bytes | no pads | Whole |
AAA= | two bytes | one pad | TwoOctets |
AA== | one byte | two pads | OneOctet |
AAAA= | not Base64 | one pad | nothing |
When it sizes the output, Java can’t tell row two from row four. It never holds a group. It holds a byte[] and a length, so decodedOutLength counts pads and subtracts:
if (src[sl - 1] == '=') {
paddings++;
if (src[sl - 2] == '=')
paddings++;
}
// ...
return 3 * (int) ((len + 3L) / 4) - paddings;
Run that on Calif’s input, sixteen whole groups and one stray =:
"A".repeat(64) + "="
Java sizes the array:
65 chars round up to 17 groups
17 × 3 − 1 pad = 50 bytes
AVX-512 finishes the tail:
1 char rounds down to 0 groups
0 × 3 − 1 pad = −1 bytes
array [=== 48 ===][2]
write [==== 64 ====]
past the end [== 62 ===]
The stray character got booked as “just padding,” twice. A length of −1 doesn’t write nothing. It writes the whole 64-byte block. Java spots the bad ending and throws right after, which is a little late.
That’s how you PHP yourself in a typed language: hold a byte[] and an int, and let arithmetic stand in for the grammar.
My decoder has no sum to get wrong. The three shapes are three types, and they’re the only groups there are:
public sealed interface Group<A extends Enum<A> & TetAlphabet<A, ?>> {
record Whole<A …>(A first, A second, A third, A fourth)
implements Group<A> { … }
record TwoOctets<A …>(A first, A second, A third)
implements Group<A> { … }
record OneOctet<A …>(A first, A second)
implements Group<A> { … }
}
An A is a constant of the alphabet: one of the 64 squares in the table above, as an enum. = isn’t one of them. It’s read as a Pad, a different type, and no group has a field that could hold one. No group has fewer than two symbols either, so row four can’t be built, never mind sized. A short group won’t even construct if its filler bits aren’t zero:
public TwoOctets {
final int filler = third.ordinal() & FILLER;
Exceptional.demand(() -> filler == 0,
"the bits after the last octet are not zero");
}
The reader doesn’t count anything either. It knows where in a group it is, and each place says what a pad means there:
reader.place = switch (reader.place) {
case START -> throw new DemandFailedException("a pad begins a group");
case FIRST -> throw new DemandFailedException("the last symbol carries no octet");
case SECOND -> Place.ONE_PAD;
case THIRD -> {
new Group.TwoOctets<>(reader.first, reader.second, reader.third).octets(to);
yield Place.PADDED;
}
case ONE_PAD -> {
new Group.OneOctet<>(reader.first, reader.second).octets(to);
yield Place.PADDED;
}
case PADDED, ENDED -> throw new DemandFailedException("a pad follows the last group");
};
That’s the whole grammar of padding, written down. There’s no default, so if I ever add a place, the compiler makes me say what a pad does there. Nothing is counted, so nothing can be miscounted.
Run Calif’s input through it:
"A".repeat(64) + "="
The reader builds groups:
16 × AAAA is 16 × Whole
each hands back 3 bytes
Then a pad arrives:
the reader is at START
a pad means nothing there, so it throws
groups [=== 48 ===]
write [=== 48 ===]
past the end: nothing
Calif’s input gets one answer: a pad begins a group.
How it could have been written, even then
java.util.Base64 shipped in 2014. Sealed types and records landed in 2021. So was any of this on the table when the decoder was written? All of it was. Here’s the same design in the Java of the day.
Start with the six bits. The only way to get a Sextet is to hand its constructor a character from the table above:
final class Sextet {
private static final String ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "0123456789+/";
final int value;
Sextet(char symbol) {
value = ALPHABET.indexOf(symbol);
if (value < 0)
throw new IllegalArgumentException(
symbol + " is no symbol of RFC 4648 §4's alphabet");
}
}
Hand it = and it throws, so nothing past this constructor ever holds a pad.
Then the three shapes. sealed is a promise that these are the only groups there are. In 2014 you made that promise with a private constructor. Only classes nested inside InputGroup can call it, so only they can extend it. Java has allowed that since 1997.
abstract class InputGroup {
private InputGroup() { }
abstract byte[] octets();
static final class Whole extends InputGroup {
private final Sextet first, second, third, fourth;
Whole(Sextet first, Sextet second, Sextet third, Sextet fourth) {
this.first = first;
this.second = second;
this.third = third;
this.fourth = fourth;
}
byte[] octets() {
return new byte[] {
(byte) (first.value << 2 | second.value >> 4),
(byte) (second.value << 4 | third.value >> 2),
(byte) (third.value << 6 | fourth.value)};
}
}
static final class TwoOctets extends InputGroup { … }
static final class OneOctet extends InputGroup { … }
}
octets() is the six-bit figure run backwards. TwoOctets is the same with three Sextets and OneOctet with two, and each checks that its filler bits are zero. It’s more typing than a record for the same guarantee: a group is one of three shapes, and each shape knows its own bytes.
Last, the reader. It builds one group at a time and asks each for its bytes:
final class Decoder {
private final String text;
private int at;
Decoder(String text) {
this.text = text;
}
byte[] octets() {
ByteArrayOutputStream octets = new ByteArrayOutputStream();
while (at < text.length()) {
byte[] group = group().octets();
octets.write(group, 0, group.length);
}
return octets.toByteArray();
}
private InputGroup group() {
Sextet first = sextet();
Sextet second = sextet();
if (closes("=="))
return new InputGroup.OneOctet(first, second);
Sextet third = sextet();
if (closes("="))
return new InputGroup.TwoOctets(first, second, third);
return new InputGroup.Whole(first, second, third, sextet());
}
private Sextet sextet() {
if (at == text.length())
throw new IllegalArgumentException(
"the text ends where a symbol is due");
return new Sextet(text.charAt(at++));
}
private boolean closes(String pads) {
if (!text.startsWith("=", at))
return false;
if (!text.substring(at).equals(pads))
throw new IllegalArgumentException(
"the text must end in " + pads);
at = text.length();
return true;
}
}
Look at what isn’t there. Nothing counts pads, and nothing works out how long the output will be before reading it. A pad is only ever the end of the text, right after a short group. The output grows by whatever each group hands back.
Run Calif’s input through it:
"A".repeat(64) + "="
The reader builds groups:
16 × AAAA is 16 × Whole
each hands back 3 bytes
Then it wants a 17th:
a group starts with a Sextet
= isn't one, so it throws
groups [=== 48 ===]
write [=== 48 ===]
past the end: nothing
Same input, same stray character. This time the worst it can do is throw: = is no symbol of RFC 4648 §4's alphabet.
All of it compiles with javac --release 8. The language was never the problem. Java could already say “a group is one of these three things” in 2014. java.util.Base64 never said it.
Performance tuning
So how fast is it? I ran JMH against java.util.Base64 on a 3 MiB message, and, sure enough, mine was slower. Of course it was. Calif reports the JDK hands the work to hand-rolled assembly on the affected processors. That’s very hard to beat in pure Java. It’s also where the bug lived.
Decoding 3 MiB of padded Base64, at the start
java.util.Base64 1.6 ms 7.3 MB allocated
mine 127.5 ms 14.7 MB allocated
Eighty times slower. But I wanted to see how close I could get while staying safe. So I started measuring and refactoring, one change at a time.
The garbage went first. A profile showed that every byte I allocated beyond the answer was a copy of the whole message, made because whoever was filling a buffer didn’t know how much was coming. So now the count travels with the data, as an estimate, and the output’s room is made once. It’s a guess and it’s treated like one: more bytes than guessed and the room grows, fewer and it’s trimmed, and no write ever trusts it. Decoding went from 14.7 MB to 3.15 MB, less than half of what the JDK allocates.
It wasn’t one millisecond faster. Garbage wasn’t the problem.
The time was in the plumbing. Every symbol went through a chain of stream stages, one element at a time. I replaced those with small hand-written iterators that do the same job in one pass. That took about a third off.
Then came the one I was sure wouldn’t matter.
In my library encoded data is a walk of symbols. A symbol knows its glyph, and a glyph knows the character it’s written as. So writing the text out asked two questions per symbol:
text.append(symbol.glyph().character());
A profile put 29% of encoding time in character(). I read the method. It’s return letter;. A field read. I said out loud that removing it was diminishing returns. Then I tried it anyway. Each constant of the alphabet keeps its character, and a symbol answers for itself:
public enum Base64 implements TetAlphabet<Base64, Bits6<Bit>> {
UPPER_A(UppercaseLetter.A), … SOLIDUS(Punctuation.SOLIDUS);
private final Graphic glyph;
private final char character;
Base64(final Graphic glyph) {
this.glyph = glyph;
this.character = glyph.character();
}
@Override
public char character() {
return character;
}
}
text.append(symbol.character());
Encoding with padding, JMH, mean of 9 one-second samples
(3 JVMs × 3, after 2 warm-ups each), one machine, one boot
before after
3 MiB 63.1 ± 0.4 ms 29.5 ± 0.2 ms
1,024 B 12.0 ± 2.2 µs 10.7 ± 1.3 µs
Half the time, gone, for one field. Not 29%. 53%.
Here’s my reading of it. The body of character() was never the cost. The call was. Graphic is an interface, and five enums implement it: uppercase letters, lowercase letters, digits, punctuation and the space. Base64 text mixes four of them, symbol by symbol. The JIT will inline a call when it has seen one or two classes on the receiving end. See a third and it gives up and looks the method up every time. Worse, a call it can’t inline is a wall in the middle of the loop, and it stops optimizing around it. That’s the part a profiler can’t show you: it charged character() for its own time, and spread the rest across everything nearby.
After the change the loop calls symbol.character(), and a symbol is one of two classes: the alphabet or the pad. Two is fine. I haven’t read the compiled code to prove that’s what happened, and the 1,024-byte numbers are too noisy to call. The 3 MiB ones aren’t.
Measure the thing you’re sure about.
Reading had one of those too. Each character was looked up as a glyph and then matched to its constant by a two-level switch, four million times over. Base64 text has 65 distinct characters. Now the reader remembers what each one read as, and decoding dropped from 81 ms to 33.
And then I caught myself. Somewhere along the way, between making one codec serve base16, base32 and base64 and making it fast, the three types had gone. In their place sat a counter, and a sum at the end of the text: are these the pads this group needs? The exact move this article is about.
Ruh roh, Raggy.
So I put the types back, braced to pay for it. It got faster. By another third.
A group turns out to be the right unit of work. The version with the sum pushed every symbol through a pad counter and then through a bit accumulator. The typed version takes four symbols and asks the group for its bytes:
public byte high() {
return (byte) (first.ordinal() << 2 | second.ordinal() >> 4);
}
public byte middle() {
return (byte) (second.ordinal() << 4 | third.ordinal() >> 2);
}
public byte low() {
return (byte) (third.ordinal() << 6 | fourth.ordinal());
}
It’s the six-bit figure again, run backwards, on a Whole.
There was one wrinkle. At first every group was a real allocation, a million little records for 3 MiB, and decoding went from 3.15 MB back up to 36.7. The JIT’s own log said why. A group handed its bytes to a callback, and the JIT wouldn’t inline that method: 311 nodes against a limit of 300. So the reader asks the group for its three bytes instead. Those inline, and the record never gets allocated. It’s still a type. It’s just free.
3 MiB of padded Base64, JMH, one machine, one day
mean of 15 one-second samples across 3 JVMs
decode encode
java.util.Base64 1.6 ms 7.3 MB 1.6 ms 8.4 MB
mine, at the start 127.5 ms 14.7 MB 98.5 ms 67.1 MB
mine, now 22.8 ms 3.2 MB 20.3 ms 11.5 MB
Still about thirteen times slower than hand-written assembly. Five times faster than where I started, on less memory than the JDK takes to decode. A kilobyte takes eight microseconds.
They say fast code has to be ugly. The fastest version I have is the one where the bad input can’t be built. I never traded safety for speed, and the step where I took safety back was worth a third.
I know what alphabet I’ll accept and what a complete group looks like. Give my decoder anything else and it throws.
import software.visionary.base64.rfc4648.Base64;
import software.visionary.base64.rfc4648.Factory;
import software.visionary.rfc4648.Codec;
Codec<Base64> base64 = Factory.PADDED.create();
byte[] key = base64.serialize(base64.read(headerValue));
That’s the call our WebSocket code gets to make. It’s on Maven Central as software.visionary:base64:2026.10.13, beside base16, base32 and base45. They read and write their groups through rfc4648, over the symbols of cuneiform.codec and the bits of wheeler.tets. Want software.visionary.base64 for your own product? Talk to me about a license. Got a 250 KB library and a sneaking suspicion you only need four? Hire me. I like those jobs.