Hardware Ed25519 on the J3R452: recovering the JCOPX API from a CAP file
The J3R452 is a Java Card 3.0.5 Classic card running NXP JCOP 4.5. Its firmware contains a private JCOP eXtended (JCOPX) package that implements Ed25519 signing, verification and X25519 key agreement; the card-side library only calls into it. Curve25519-JavaCard is that thin layer. Its README quotes about 220 ms for an EdDSA signature and about 50 ms for X25519, says the full source is not provided for legal reasons, and invites anyone to disassemble the .cap to check that nothing funny is going on.
I took the invitation. I unpacked Curve25519.cap, recovered the private JCOPX interface it calls from the tokens and bytecode, rewrote the wrapper from source so that it links identically, and ran 20 checks on a real card, most of them byte-for-byte against an independent RFC 8032 / RFC 7748 implementation. This post is the write-up: what the CAP actually contains, how the private API was recovered, how the converter can be made to link against a package that only exists in card ROM, and what the card said when tested — including an X25519 byte-order trap the original README never mentions, and a J3R180 that refuses to load either version.
Where the hardware actually is
Section titled “Where the hardware actually is”First, what “hardware implementation” means here. Curve25519.cap is actually a JAR (ZIP) holding the Header, Import, ConstantPool, Method and other components, not a bare CAP binary. Its Import component lists exactly four packages:
| import token | AID | version |
|---|---|---|
| 0 | a0000000620001 (java/lang) |
1.0 |
| 1 | a0000000620102 (javacard/security) |
1.6 |
| 2 | a0000000620101 (javacard/framework) |
1.6 |
| 3 | d276000085304a434f5058 (JCOPX) |
1.24 |
The curve arithmetic is not in the CAP. The CAP stores 32-byte keys, converts byte order, creates JCOPX key objects and calls them, plus some transaction and exception handling. In other words, it is a wrapper of a few hundred lines; the expensive scalar multiplication and SHA-512 live in the card’s ROM/firmware. That is why reconstructing it does not require implementing Curve25519 — it requires getting the calls into the firmware exactly right.
The call stack looks roughly like this:
applet └─ org.suut.javacard.pki.curve25519 (CAP, this repo) └─ JCOPX d276000085304a434f5058 (card ROM) └─ Ed25519 / X25519 in firmwareThat is harder than it sounds, because a CAP does not store names.
A CAP has tokens, not names
Section titled “A CAP has tokens, not names”When a Java Card CAP links against another package, it records only a triple: package token, class token, method token. It does not store the class name, the method name, or the argument types. The ConstantPool of Curve25519.cap contains entries like these:
83 01 02 static method pkg=3 cls=1 tok=283 01 03 static method pkg=3 cls=1 tok=383 01 0d static method pkg=3 cls=1 tok=1383 0b 01 static method pkg=3 cls=11 tok=183 0b 02 static method pkg=3 cls=11 tok=283 09 class pkg=3 cls=983 0a class pkg=3 cls=10pkg=3 is JCOPX. 83 marks an external reference; the class and method tokens are slots in the ROM package. On their own they still do not say whether (1,2) is signing or verification. The call sites in the Method component supply the argument counts and the bytecode, and with the Java Card calling convention that is enough to recover the signatures.
The recovered JCOPX surface looks like this.
Class token 1, the curve operations, all static:
| method token | recovered signature | meaning |
|---|---|---|
| 2 | short sign(JopxPrivateKey, byte type, byte[] hash, short hashOffset, short hashLength, byte[] signature, short signatureOffset) |
EdDSA signature; returns 64 |
| 3 | short verify(JopxPublicKey, byte type, byte[] hash, short hashOffset, short hashLength, byte[] signature, short signatureOffset, short signatureLength) |
EdDSA verification; returns 0x5A5A on success |
| 13 | short keyAgreement(JopxPrivateKey, JopxPublicKey, byte type, byte[] output, short outputOffset) |
X25519; returns 32 |
Class token 11, the key factory:
| method token | signature | meaning |
|---|---|---|
| 1 | Object createKey(byte algorithm, byte memoryType) |
allocate an empty key |
| 2 | void genKeyPair(JopxPrivateKey, JopxPublicKey) |
generate a fresh key pair |
Class tokens 9 and 10 are the private-key and public-key interfaces, each with seven methods: clearKey, getSize, getType, isInitialized, getKeyMemoryType, importKey, exportKey, method tokens 0 through 6.
The type argument is 0xA3 on the EdDSA path and 0xA4 on the X25519 path; those values also come from the bytecode. The class and method names are mine. The CAP stores no names, and NXP does not publish a JCOPX export file (the API is under NDA). Names do not affect linking: the converter writes only the tokens into the CAP, so any naming that produces the same tokens links identically.
Making the converter link against a package that only exists on the card
Section titled “Making the converter link against a package that only exists on the card”Once the signatures were recovered, the next problem was the build. The Java Card converter needs a .exp export file for every imported package; JCOPX’s .exp is not in any public SDK.
The workaround is a stand-in package:
- Write a
jopxpackage declaring the classes and interfaces recovered above. - Convert it to
jopx.expwith the converter. - Rewrite the class and method tokens in that stub exp to the values the card uses, with
tools/ExpPatch.java. - Compile the library against the patched exp and convert it to a CAP.
Step 3 is the core. The converter assigns tokens in its own order (interfaces, classes, methods in declaration order) and cannot produce the JCOPX layout directly: the curve operations class is token 1 with methods 2, 3 and 13, the key factory is token 11 with methods 1 and 2, and the key interfaces are tokens 9 and 10. Since a CAP only links by token, the trick is to let the converter produce a legal exp and then patch it to the target tokens:
privateKey.setClassToken(9);publicKey.setClassToken(10);curve25519.setClassToken(1);keyFactory.setClassToken(11);
setMethodToken(curve25519, "sign", "(L...;B[BSS[BS)S", 2);setMethodToken(curve25519, "verify", "(L...;B[BSS[BSS)S", 3);setMethodToken(curve25519, "keyAgreement", "(L...;L...;B[BS)S", 13);There is also a hard converter rule: the exported method tokens of a class must be consecutive from 0. The curve operations class needs 2, 3 and 13, and the key factory needs 1 and 2, so the gaps must be filled. That is why the stub contains a pile of m0, m1 and m4 through m12 filler methods. They are never called; they exist only to make the token numbering legal.
Whether this counts as a successful reconstruction has a hard test: the regenerated curve25519.exp is byte-for-byte identical to the 1553-byte export file inside curve25519.jar. cmp prints nothing. The export file is the interface other packages compile against, so an exact match means the class tokens, method tokens, access flags, descriptor pool and field constants all line up. The Header, Import and StaticField components are also byte-for-byte identical; the ConstantPool has the same 25 entries and the same external references; the Method component has the same four exception handlers.
The CAP itself is not byte-identical, and should not be expected to be: the original was built by a different converter build, which lays out methods and constant-pool entries in its own order. For a library package, what matters is the export file and the token triples of the external calls, and both match.
One warning has to be written in stone: the stub jopx package must never be installed on a card. Its AID is the AID of the JCOPX package already in the card’s ROM; installing it would shadow the real package and every call would land on the stub’s return 0 methods. build.sh only converts the stub to an exp and never produces an installable CAP.
Rewriting the wrapper from source
Section titled “Rewriting the wrapper from source”The public API is unchanged: three interfaces, three classes, the same method descriptors and the same exception behaviour. The two implementation classes (Curve25519PrivateKeyImpl, Curve25519PublicKeyImpl) are package-private and therefore not exported; their class token is 255, as in the original. They hold the JCOPX key objects and forward the calls.
The part that needs care is byte order. JCOPX works big-endian internally while RFC 7748 / RFC 8032 use little-endian, so the wrapper converts in the middle:
- public keys:
getW/setWreverse the 32 bytes; - signatures:
R || S, two 32-byte halves, each reversed; - private keys:
getS/setSpass the bytes through unchanged.
That last rule is the original behaviour, and it is where the card later bit me. Signing and exchange both do the same kind of reversal; the signing code looks roughly like this:
short length = JcopxCurve25519.sign(key, (byte) 0xA3, inBuff, inOffset, inLength, buf, (short) 0);if (length != 64) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);}try { JCSystem.beginTransaction(); for (short i = 0; i < 32; i++) { outBuff[(short) (outOffset + 31 - i)] = buf[i]; outBuff[(short) (outOffset + 63 - i)] = buf[(short) (32 + i)]; } JCSystem.commitTransaction();} catch (Throwable e) { try { JCSystem.abortTransaction(); } catch (TransactionException alreadyAborted) { // a failed commit has already rolled the transaction back } throw e;}The transaction nesting was recovered from the bytecode as well: beginTransaction sits inside the try, abortTransaction inside the catch, wrapped in another catch for TransactionException. A failed commit has already rolled back, so aborting again throws; the original swallows that second exception and rethrows the first. It does not matter on the happy path, but it does change the behaviour on the error path, so it was kept.
The buffers are CLEAR_ON_DESELECT transient arrays, so signature material and shared secrets do not linger in persistent memory. That is also what the original does.
On the card
Section titled “On the card”The test card is a J3R452; gp --info reports ICType=D600, batch 4528, fabricated 2025-12-02. Its GlobalPlatform keys were first replaced with the well-known development keys 4041…4F (this is a lab card; do not do that to a production card), then the packages were loaded:
curve25519.cap loaded: org.suut.javacard.pki.curve25519 FF00025519cardtest.cap loaded: org.suut.javacard.pki.curve25519.cardtest F0435552564501Those two lines are the decisive evidence. When the loader finishes a package it resolves every external reference; a class token or method token that does not exist on the card makes the last block fail with 6A80. Loading succeeded, which means the card’s JCOPX really does have class 1 (sign / verify / keyAgreement), classes 9/10 (the private and public key interfaces) and class 11 (createKey / genKeyPair), with exactly the recovered method tokens, and that the card’s package is at least version 1.24.
The functional test uses a dedicated applet, one APDU per operation (01 generate a key pair, 10/11 read public/private key, 12/13 write, 30 sign, 40 verify, 50 exchange, 60 diagnostics), with exceptions mapped to 6A00 + reason or 6B00 + index instead of a bare 6F00. On the host, ApduRunner keeps a single PC/SC session open (gp -a reopens the session for every command, so it cannot drive an applet APDU by APDU), and every result is compared with an independent RFC 8032 / RFC 7748 implementation.
All 20 checks pass:
PASS import EdDSA seedPASS read back EdDSA seedPASS import EdDSA public keyPASS read back EdDSA public keyPASS sign returns 64 bytesPASS signature matches plain Ed25519 over the inputPASS verify accepts hash||signaturePASS verify rejects a modified signature SW=6982PASS import X25519 scalar (big endian)PASS import X25519 public keyPASS read back X25519 public keyPASS X25519 shared secretPASS generate EdDSA key pairPASS read generated EdDSA seedPASS generated EdDSA public key matches its seedPASS generate X25519 key pairPASS read generated X25519 scalarPASS generated X25519 public key matches its scalarPASS setW rejects a 16 byte key SW=6700PASS verify rejects a short signature SW=6700
20 checks, 0 failedA few results deserve their own paragraph:
- The card does plain Ed25519, not Ed25519ph. The signature matches
Ed25519(seed, message)exactly: the input bytes are treated as the message, and the caller decides whether to pass a message or a hash. The type byte is0xA3. - Verification returns
0x5A5Aon success. The wrapper turns that intotrue; on failure the applet returns6982. - X25519 byte order is asymmetric. Public keys and shared secrets go in and out in RFC 7748 little-endian order, but the private scalar is passed through unchanged, and JCOPX treats that scalar as big-endian. A host has to reverse an RFC little-endian scalar before
setS, and reverse whatgetSreturns (including the value produced bygenKeyPair) before feeding it to an RFC implementation. The bytecode of the released CAP does exactly this; it is not a reconstruction bug. getSize()returns 0 for these keys. It cannot be used to tell whether a key is initialised;isInitialized()is the reliable check.getKeyMemoryType()returns the memory type requested at creation (0 for persistent keys).
The first test run had Ed25519 passing immediately and the X25519 shared secret mismatching. The cause was the rule above: the test had written the RFC little-endian scalar straight into setS. After reversing it, the shared secret matched RFC 7748 section 6.1. The same run also had a wrong expectation about getSize(), so that check became an informational line.
Performance
Section titled “Performance”The numbers from --timing, measured over PC/SC including the round trip (same card, final full run):
| operation | time |
|---|---|
| EdDSA sign | 261.5 ms |
| EdDSA verify | 52.0 ms |
| X25519 exchange | 39.5 ms |
genKeyPair EdDSA |
93.5 ms |
genKeyPair X25519 |
41.4 ms |
Signing is a little above the ~220 ms the README claims, and the exchange is a little faster than the ~50 ms it claims. These numbers include the PC/SC round trip and APDU handling, so the on-card arithmetic is lower; but this is the cost an applet actually sees when it calls the library, and protocol design should budget at this order of magnitude.
A card that cannot load it: the J3R180
Section titled “A card that cannot load it: the J3R180”Before the 452 arrived I tried a J3R180 (ICType=D321, batch 4839). Neither the original Curve25519.cap nor the rebuilt library would load; the last LOAD block failed with 6A80.
That is not a reconstruction problem. I wrote a probe applet that calls JCOPX at (class token C, method token M): if both tokens resolve on the card, the LOAD succeeds; otherwise the loader reports 6A80. Scanning class tokens this way showed that the J3R180 only has classes 0 through 7; from 8 onwards everything fails, and classes 9, 10 and 11 do not exist at all. Its JCOPX is an older layout with only eight classes, while the released CAP imports version 1.24. The original CAP fails on the 180 for the same reason.
The lesson is that tokens are tied to the firmware version. JOPX_VERSION can lower the import version so that an older JCOPX passes the version check, but it cannot conjure up classes and methods the card does not have. Before switching cards, probe the target tokens rather than loading the CAP and guessing at 6A80.
Reproducing it
Section titled “Reproducing it”You need JDK 11, a Java Card 3.0.5 development kit (converter, api_classic-3.0.5.jar, api_export_files_3.0.5), plus gp.exe and a reader. Build:
./build.sh --verifyJOPX_VERSION=1.24 ./test/build-test.sh./test/install-card.shpython3 -u test/card_test.py --timingbuild.sh compiles with --release 7 so that the class files are major version 51, the only version the converter accepts; --verify prints the Import and ConstantPool components of the new CAP so the linkage can be checked without a card. JOPX_VERSION is for older cards, for example JOPX_VERSION=1.18. The test scripts assume the well-known development keys 4041…4F and that the card has already been switched to them.
The original Curve25519.cap and curve25519.jar are not modified by the build, and build/ is git-ignored. The repository also contains docs/RECONSTRUCTION.md, which records the component-by-component comparison, what has not been verified (for example JCOPX newer than 1.24), and a pre-existing bug in sample/: in the 0x40 branch the verify call sits after a throw, so it is unreachable.
Closing
Section titled “Closing”The core of this work was not elliptic-curve mathematics but a linking contract: a CAP only knows tokens, the card only knows slots in its firmware, and the export file is the interface between them. Get the tokens right and translate the byte order correctly, and the wrapper falls out; the mathematics stays in NXP’s ROM, where it does not need to be reimplemented — and should not be.
The code and documentation are in vilicvane/Curve25519-JavaCard. If you use this card for Ed25519, run test/card_test.py --self-check and the on-card tests before putting the library into a protocol.