From 4007fd129d7da013df60787fecc47e4edfea340f Mon Sep 17 00:00:00 2001
From: Sameer Singh <123424263+SameerSinghhh@users.noreply.github.com>
Date: Thu, 3 Dec 2026 17:01:02 -0800
Subject: [PATCH] Add ML-DSA (FIPS 204) signature algorithms
Adds Algorithm.MLDSA44, MLDSA65 and MLDSA87 for the ML-DSA-44, ML-DSA-65 and
ML-DSA-87 JWS algorithms defined in RFC 9964, with an MLDSAKeyProvider
interface. The library still compiles for Java 8; ML-DSA itself comes from
the JVM (Java 24+) or a registered provider such as BouncyCastle.
---
README.md | 5 +
.../com/auth0/jwt/algorithms/Algorithm.java | 88 +++++
.../auth0/jwt/algorithms/MLDSAAlgorithm.java | 154 ++++++++
.../jwt/interfaces/MLDSAKeyProvider.java | 13 +
.../jwt/algorithms/MLDSAAlgorithmTest.java | 338 ++++++++++++++++++
.../jwt/algorithms/MLDSAInteropTest.java | 113 ++++++
6 files changed, 711 insertions(+)
create mode 100644 lib/src/main/java/com/auth0/jwt/algorithms/MLDSAAlgorithm.java
create mode 100644 lib/src/main/java/com/auth0/jwt/interfaces/MLDSAKeyProvider.java
create mode 100644 lib/src/test/java/com/auth0/jwt/algorithms/MLDSAAlgorithmTest.java
create mode 100644 lib/src/test/java/com/auth0/jwt/algorithms/MLDSAInteropTest.java
diff --git a/README.md b/README.md
index 8415e32e..b339e0ba 100644
--- a/README.md
+++ b/README.md
@@ -42,9 +42,14 @@ This library is supported for Java LTS versions 8, 11, 17 and 21. For issues on
| ES256 | ECDSA256 | ECDSA with curve P-256 and SHA-256 |
| ES384 | ECDSA384 | ECDSA with curve P-384 and SHA-384 |
| ES512 | ECDSA512 | ECDSA with curve P-521 and SHA-512 |
+| ML-DSA-44 | MLDSA44 | ML-DSA-44 (FIPS 204, post-quantum) |
+| ML-DSA-65 | MLDSA65 | ML-DSA-65 (FIPS 204, post-quantum) |
+| ML-DSA-87 | MLDSA87 | ML-DSA-87 (FIPS 204, post-quantum) |
> Note - Support for ECDSA with curve secp256k1 and SHA-256 (ES256K) has been dropped since it has been [disabled in Java 15](https://www.oracle.com/java/technologies/javase/15-relnote-issues.html#JDK-8237219)
+> Note - The ML-DSA algorithms (ML-DSA-44, ML-DSA-65, ML-DSA-87, as defined for JOSE in [RFC 9964](https://www.rfc-editor.org/info/rfc9964/)) rely on the JVM for ML-DSA support, which is available natively from Java 24 onwards ([JEP 497](https://openjdk.org/jeps/497)). On earlier versions, a security provider that implements `ML-DSA` (such as [BouncyCastle](https://www.bouncycastle.org/)) must be registered; no additional provider is bundled by this library.
+
> Note - The RSASSA-PSS algorithms (PS256, PS384, PS512) rely on the JVM for RSASSA-PSS support, which is available natively from Java 11 onwards via the `SunRsaSign` provider ([JDK-8146293](https://bugs.openjdk.org/browse/JDK-8146293)). On Java 8, a security provider that implements `RSASSA-PSS` (such as [BouncyCastle](https://www.bouncycastle.org/)) must be registered on the classpath; no additional provider is bundled by this library.
> :warning: **Important security note:** JVM has a critical vulnerability for ECDSA Algorithms - [CVE-2022-21449](https://nvd.nist.gov/vuln/detail/CVE-2022-21449). Please review the details of the vulnerability and update your environment.
diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java
index dce39c37..74011bc6 100644
--- a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java
+++ b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java
@@ -4,8 +4,11 @@
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.ECDSAKeyProvider;
+import com.auth0.jwt.interfaces.MLDSAKeyProvider;
import com.auth0.jwt.interfaces.RSAKeyProvider;
+import java.security.PrivateKey;
+import java.security.PublicKey;
import java.security.interfaces.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
@@ -437,6 +440,91 @@ public static Algorithm ECDSA512(ECKey key) throws IllegalArgumentException {
}
+ /**
+ * Creates a new Algorithm instance using ML-DSA-44 (FIPS 204), a post-quantum signature algorithm.
+ * Tokens specify this as "ML-DSA-44" (RFC 9964).
+ *
+ * The JVM must have a security provider that implements ML-DSA: Java 24 and later include one,
+ * earlier versions need a provider such as BouncyCastle to be registered.
+ *
+ * @param keyProvider the provider of the Public Key and Private Key for the verify and signing instance.
+ * @return a valid ML-DSA-44 Algorithm.
+ * @throws IllegalArgumentException if the Key Provider is null.
+ */
+ public static Algorithm MLDSA44(MLDSAKeyProvider keyProvider) throws IllegalArgumentException {
+ return new MLDSAAlgorithm("ML-DSA-44", "2.16.840.1.101.3.4.3.17", 2420, keyProvider);
+ }
+
+ /**
+ * Creates a new Algorithm instance using ML-DSA-44 (FIPS 204), a post-quantum signature algorithm.
+ * Tokens specify this as "ML-DSA-44" (RFC 9964).
+ *
+ * @param publicKey the key to use in the verify instance.
+ * @param privateKey the key to use in the signing instance.
+ * @return a valid ML-DSA-44 Algorithm.
+ * @throws IllegalArgumentException if both provided Keys are null.
+ */
+ public static Algorithm MLDSA44(PublicKey publicKey, PrivateKey privateKey) throws IllegalArgumentException {
+ return MLDSA44(MLDSAAlgorithm.providerForKeys(publicKey, privateKey));
+ }
+
+ /**
+ * Creates a new Algorithm instance using ML-DSA-65 (FIPS 204), a post-quantum signature algorithm.
+ * Tokens specify this as "ML-DSA-65" (RFC 9964).
+ *
+ * The JVM must have a security provider that implements ML-DSA: Java 24 and later include one,
+ * earlier versions need a provider such as BouncyCastle to be registered.
+ *
+ * @param keyProvider the provider of the Public Key and Private Key for the verify and signing instance.
+ * @return a valid ML-DSA-65 Algorithm.
+ * @throws IllegalArgumentException if the Key Provider is null.
+ */
+ public static Algorithm MLDSA65(MLDSAKeyProvider keyProvider) throws IllegalArgumentException {
+ return new MLDSAAlgorithm("ML-DSA-65", "2.16.840.1.101.3.4.3.18", 3309, keyProvider);
+ }
+
+ /**
+ * Creates a new Algorithm instance using ML-DSA-65 (FIPS 204), a post-quantum signature algorithm.
+ * Tokens specify this as "ML-DSA-65" (RFC 9964).
+ *
+ * @param publicKey the key to use in the verify instance.
+ * @param privateKey the key to use in the signing instance.
+ * @return a valid ML-DSA-65 Algorithm.
+ * @throws IllegalArgumentException if both provided Keys are null.
+ */
+ public static Algorithm MLDSA65(PublicKey publicKey, PrivateKey privateKey) throws IllegalArgumentException {
+ return MLDSA65(MLDSAAlgorithm.providerForKeys(publicKey, privateKey));
+ }
+
+ /**
+ * Creates a new Algorithm instance using ML-DSA-87 (FIPS 204), a post-quantum signature algorithm.
+ * Tokens specify this as "ML-DSA-87" (RFC 9964).
+ *
+ * The JVM must have a security provider that implements ML-DSA: Java 24 and later include one,
+ * earlier versions need a provider such as BouncyCastle to be registered.
+ *
+ * @param keyProvider the provider of the Public Key and Private Key for the verify and signing instance.
+ * @return a valid ML-DSA-87 Algorithm.
+ * @throws IllegalArgumentException if the Key Provider is null.
+ */
+ public static Algorithm MLDSA87(MLDSAKeyProvider keyProvider) throws IllegalArgumentException {
+ return new MLDSAAlgorithm("ML-DSA-87", "2.16.840.1.101.3.4.3.19", 4627, keyProvider);
+ }
+
+ /**
+ * Creates a new Algorithm instance using ML-DSA-87 (FIPS 204), a post-quantum signature algorithm.
+ * Tokens specify this as "ML-DSA-87" (RFC 9964).
+ *
+ * @param publicKey the key to use in the verify instance.
+ * @param privateKey the key to use in the signing instance.
+ * @return a valid ML-DSA-87 Algorithm.
+ * @throws IllegalArgumentException if both provided Keys are null.
+ */
+ public static Algorithm MLDSA87(PublicKey publicKey, PrivateKey privateKey) throws IllegalArgumentException {
+ return MLDSA87(MLDSAAlgorithm.providerForKeys(publicKey, privateKey));
+ }
+
+
public static Algorithm none() {
return new NoneAlgorithm();
}
diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/MLDSAAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/MLDSAAlgorithm.java
new file mode 100644
index 00000000..200bef5f
--- /dev/null
+++ b/lib/src/main/java/com/auth0/jwt/algorithms/MLDSAAlgorithm.java
@@ -0,0 +1,154 @@
+package com.auth0.jwt.algorithms;
+
+import com.auth0.jwt.exceptions.SignatureGenerationException;
+import com.auth0.jwt.exceptions.SignatureVerificationException;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import com.auth0.jwt.interfaces.MLDSAKeyProvider;
+
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SignatureException;
+import java.util.Base64;
+
+/**
+ * Subclass representing an ML-DSA (FIPS 204) signing algorithm, used as defined for JOSE in RFC 9964:
+ * the pure variant, with an empty context string, over the JWS signing input.
+ *
+ * This class is thread-safe.
+ */
+class MLDSAAlgorithm extends Algorithm {
+
+ private static final String FAMILY = "ML-DSA";
+
+ private final MLDSAKeyProvider keyProvider;
+ private final CryptoHelper crypto;
+ private final String oid;
+ private final int signatureLength;
+
+ //Visible for testing
+ MLDSAAlgorithm(CryptoHelper crypto, String id, String oid, int signatureLength, MLDSAKeyProvider keyProvider)
+ throws IllegalArgumentException {
+ super(id, id);
+ if (keyProvider == null) {
+ throw new IllegalArgumentException("The Key Provider cannot be null.");
+ }
+ this.keyProvider = keyProvider;
+ this.crypto = crypto;
+ this.oid = oid;
+ this.signatureLength = signatureLength;
+ }
+
+ MLDSAAlgorithm(String id, String oid, int signatureLength, MLDSAKeyProvider keyProvider)
+ throws IllegalArgumentException {
+ this(new CryptoHelper(), id, oid, signatureLength, keyProvider);
+ }
+
+ @Override
+ public void verify(DecodedJWT jwt) throws SignatureVerificationException {
+ try {
+ byte[] signatureBytes = Base64.getUrlDecoder().decode(jwt.getSignature());
+ PublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId());
+ if (publicKey == null) {
+ throw new IllegalStateException("The given Public Key is null.");
+ }
+ validateKey(publicKey);
+ if (signatureBytes.length != signatureLength) {
+ throw new SignatureException("Invalid " + getName() + " signature length.");
+ }
+ boolean valid = crypto.verifySignatureFor(
+ getDescription(), publicKey, jwt.getHeader(), jwt.getPayload(), signatureBytes);
+ if (!valid) {
+ throw new SignatureVerificationException(this);
+ }
+ } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException
+ | IllegalArgumentException | IllegalStateException e) {
+ throw new SignatureVerificationException(this, e);
+ }
+ }
+
+ @Override
+ public byte[] sign(byte[] headerBytes, byte[] payloadBytes) throws SignatureGenerationException {
+ try {
+ PrivateKey privateKey = signingKey();
+ return checkLength(crypto.createSignatureFor(getDescription(), privateKey, headerBytes, payloadBytes));
+ } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) {
+ throw new SignatureGenerationException(this, e);
+ }
+ }
+
+ @Override
+ public byte[] sign(byte[] contentBytes) throws SignatureGenerationException {
+ try {
+ PrivateKey privateKey = signingKey();
+ return checkLength(crypto.createSignatureFor(getDescription(), privateKey, contentBytes));
+ } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) {
+ throw new SignatureGenerationException(this, e);
+ }
+ }
+
+ @Override
+ public String getSigningKeyId() {
+ return keyProvider.getPrivateKeyId();
+ }
+
+ private PrivateKey signingKey() throws InvalidKeyException {
+ PrivateKey privateKey = keyProvider.getPrivateKey();
+ if (privateKey == null) {
+ throw new IllegalStateException("The given Private Key is null.");
+ }
+ validateKey(privateKey);
+ return privateKey;
+ }
+
+ private byte[] checkLength(byte[] signature) throws SignatureException {
+ if (signature.length != signatureLength) {
+ throw new SignatureException("Unexpected " + getName() + " signature length.");
+ }
+ return signature;
+ }
+
+ /**
+ * Rejects a key that is not an ML-DSA key, or that belongs to another ML-DSA parameter set.
+ * Providers name these keys differently: the parameter set ("ML-DSA-65"), the family ("ML-DSA") or the
+ * algorithm OID. When only the family is reported the security provider enforces the parameter set.
+ */
+ private void validateKey(Key key) throws InvalidKeyException {
+ String keyAlgorithm = key.getAlgorithm();
+ if (keyAlgorithm == null) {
+ throw new InvalidKeyException("The given Key has no algorithm.");
+ }
+ boolean matches = keyAlgorithm.equalsIgnoreCase(getName())
+ || keyAlgorithm.equalsIgnoreCase(FAMILY)
+ || keyAlgorithm.equals(oid);
+ if (!matches) {
+ throw new InvalidKeyException(
+ "The given Key is for " + keyAlgorithm + " and cannot be used with " + getName() + ".");
+ }
+ }
+
+ //Visible for testing
+ static MLDSAKeyProvider providerForKeys(final PublicKey publicKey, final PrivateKey privateKey) {
+ if (publicKey == null && privateKey == null) {
+ throw new IllegalArgumentException("Both provided Keys cannot be null.");
+ }
+ return new MLDSAKeyProvider() {
+ @Override
+ public PublicKey getPublicKeyById(String keyId) {
+ return publicKey;
+ }
+
+ @Override
+ public PrivateKey getPrivateKey() {
+ return privateKey;
+ }
+
+ @Override
+ public String getPrivateKeyId() {
+ return null;
+ }
+ };
+ }
+}
diff --git a/lib/src/main/java/com/auth0/jwt/interfaces/MLDSAKeyProvider.java b/lib/src/main/java/com/auth0/jwt/interfaces/MLDSAKeyProvider.java
new file mode 100644
index 00000000..3cd6cf34
--- /dev/null
+++ b/lib/src/main/java/com/auth0/jwt/interfaces/MLDSAKeyProvider.java
@@ -0,0 +1,13 @@
+package com.auth0.jwt.interfaces;
+
+import java.security.PrivateKey;
+import java.security.PublicKey;
+
+/**
+ * ML-DSA (FIPS 204) Public/Private Key provider.
+ *
+ * ML-DSA keys have no dedicated type in {@code java.security.interfaces} on the Java versions this library
+ * supports, so the general {@link PublicKey} and {@link PrivateKey} types are used.
+ */
+public interface MLDSAKeyProvider extends KeyProvider {
+}
diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/MLDSAAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/MLDSAAlgorithmTest.java
new file mode 100644
index 00000000..537cae00
--- /dev/null
+++ b/lib/src/test/java/com/auth0/jwt/algorithms/MLDSAAlgorithmTest.java
@@ -0,0 +1,338 @@
+package com.auth0.jwt.algorithms;
+
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.exceptions.AlgorithmMismatchException;
+import com.auth0.jwt.exceptions.SignatureGenerationException;
+import com.auth0.jwt.exceptions.SignatureVerificationException;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import com.auth0.jwt.interfaces.MLDSAKeyProvider;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.AfterClass;
+import org.junit.Assume;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.Assert.assertThrows;
+
+/**
+ * These tests register BouncyCastle as the preferred provider so that ML-DSA is available on every Java version.
+ */
+public class MLDSAAlgorithmTest {
+
+ private static final Provider bcProvider = new BouncyCastleProvider();
+ private static final String[] SETS = {"ML-DSA-44", "ML-DSA-65", "ML-DSA-87"};
+ private static final int[] SIGNATURE_LENGTHS = {2420, 3309, 4627};
+ private static final Map keys = new LinkedHashMap<>();
+ private static final Map otherKeys = new LinkedHashMap<>();
+ private static KeyPair rsaKeys;
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ Security.insertProviderAt(bcProvider, 1);
+ for (String set : SETS) {
+ keys.put(set, KeyPairGenerator.getInstance(set, bcProvider).generateKeyPair());
+ otherKeys.put(set, KeyPairGenerator.getInstance(set, bcProvider).generateKeyPair());
+ }
+ KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
+ rsa.initialize(2048);
+ rsaKeys = rsa.generateKeyPair();
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ Security.removeProvider(bcProvider.getName());
+ }
+
+ private static Algorithm algorithm(String set, PublicKey publicKey, PrivateKey privateKey) {
+ switch (set) {
+ case "ML-DSA-44":
+ return Algorithm.MLDSA44(publicKey, privateKey);
+ case "ML-DSA-65":
+ return Algorithm.MLDSA65(publicKey, privateKey);
+ default:
+ return Algorithm.MLDSA87(publicKey, privateKey);
+ }
+ }
+
+ private static Algorithm algorithm(String set) {
+ return algorithm(set, keys.get(set).getPublic(), keys.get(set).getPrivate());
+ }
+
+ private static String flip(String token, int part) {
+ String[] parts = token.split("\\.");
+ byte[] bytes = Base64.getUrlDecoder().decode(parts[part]);
+ bytes[bytes.length / 2] ^= 0x01;
+ parts[part] = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return String.join(".", parts);
+ }
+
+ @Test
+ public void shouldSignAndVerifyWithEveryParameterSet() {
+ for (int i = 0; i < SETS.length; i++) {
+ Algorithm algorithm = algorithm(SETS[i]);
+ String token = JWT.create().withIssuer("auth0").withClaim("n", i).sign(algorithm);
+
+ DecodedJWT decoded = JWT.require(algorithm).withIssuer("auth0").build().verify(token);
+ assertThat(decoded.getAlgorithm(), is(SETS[i]));
+ assertThat(decoded.getClaim("n").asInt(), is(i));
+ assertThat(algorithm.getName(), is(SETS[i]));
+ assertThat(Base64.getUrlDecoder().decode(decoded.getSignature()).length, is(SIGNATURE_LENGTHS[i]));
+ }
+ }
+
+ @Test
+ public void shouldProduceSignaturesThatThePlainJcaApiVerifies() throws Exception {
+ for (String set : SETS) {
+ String token = JWT.create().withSubject("interop").sign(algorithm(set));
+ String[] parts = token.split("\\.");
+
+ Signature verifier = Signature.getInstance(set, bcProvider);
+ verifier.initVerify(keys.get(set).getPublic());
+ verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8));
+ assertThat(verifier.verify(Base64.getUrlDecoder().decode(parts[2])), is(true));
+ }
+ }
+
+ @Test
+ public void shouldVerifySignaturesMadeByThePlainJcaApi() throws Exception {
+ for (String set : SETS) {
+ String header = Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(("{\"alg\":\"" + set + "\",\"typ\":\"JWT\"}").getBytes(StandardCharsets.UTF_8));
+ String payload = Base64.getUrlEncoder().withoutPadding()
+ .encodeToString("{\"iss\":\"auth0\"}".getBytes(StandardCharsets.UTF_8));
+ Signature signer = Signature.getInstance(set, bcProvider);
+ signer.initSign(keys.get(set).getPrivate());
+ signer.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
+ String token = header + "." + payload + "."
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign());
+
+ JWT.require(algorithm(set)).withIssuer("auth0").build().verify(token);
+ }
+ }
+
+ @Test
+ public void shouldSignWithTheDeprecatedSingleArrayMethod() {
+ for (String set : SETS) {
+ Algorithm algorithm = algorithm(set);
+ String content = "eyJhbGciOiJub25lIn0.eyJpc3MiOiJhdXRoMCJ9";
+ byte[] signature = algorithm.sign(content.getBytes(StandardCharsets.UTF_8));
+ String token = content + "." + Base64.getUrlEncoder().withoutPadding().encodeToString(signature);
+ algorithm.verify(JWT.decode(token));
+ }
+ }
+
+ @Test
+ public void shouldFailWhenThePayloadIsChanged() {
+ for (String set : SETS) {
+ Algorithm algorithm = algorithm(set);
+ String token = JWT.create().withIssuer("auth0").withClaim("admin", false).sign(algorithm);
+ String[] parts = token.split("\\.");
+ String forged = Base64.getUrlEncoder().withoutPadding()
+ .encodeToString("{\"iss\":\"auth0\",\"admin\":true}".getBytes(StandardCharsets.UTF_8));
+ String tampered = parts[0] + "." + forged + "." + parts[2];
+ assertThrows(set, SignatureVerificationException.class, () -> algorithm.verify(JWT.decode(tampered)));
+ }
+ }
+
+ @Test
+ public void shouldFailWhenTheSignatureIsChanged() {
+ for (String set : SETS) {
+ Algorithm algorithm = algorithm(set);
+ String token = JWT.create().withIssuer("auth0").sign(algorithm);
+ assertThrows(set, SignatureVerificationException.class,
+ () -> algorithm.verify(JWT.decode(flip(token, 2))));
+ }
+ }
+
+ @Test
+ public void shouldFailWhenTheSignatureHasTheWrongLength() {
+ for (String set : SETS) {
+ Algorithm algorithm = algorithm(set);
+ String token = JWT.create().withIssuer("auth0").sign(algorithm);
+ String[] parts = token.split("\\.");
+ byte[] signature = Base64.getUrlDecoder().decode(parts[2]);
+ byte[] shorter = java.util.Arrays.copyOf(signature, signature.length - 1);
+ byte[] longer = java.util.Arrays.copyOf(signature, signature.length + 1);
+ for (byte[] bad : new byte[][]{shorter, longer, new byte[0]}) {
+ String tampered = parts[0] + "." + parts[1] + "."
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(bad);
+ SignatureVerificationException e = assertThrows(set, SignatureVerificationException.class,
+ () -> algorithm.verify(JWT.decode(tampered)));
+ assertThat(e.getCause(), is(instanceOf(SignatureException.class)));
+ }
+ }
+ }
+
+ @Test
+ public void shouldFailWhenVerifyingWithAnotherKey() {
+ for (String set : SETS) {
+ String token = JWT.create().withIssuer("auth0").sign(algorithm(set));
+ Algorithm other = algorithm(set, otherKeys.get(set).getPublic(), null);
+ assertThrows(set, SignatureVerificationException.class, () -> other.verify(JWT.decode(token)));
+ }
+ }
+
+ @Test
+ public void shouldRejectAKeyFromAnotherParameterSet() {
+ for (String set : SETS) {
+ for (String keySet : SETS) {
+ if (set.equals(keySet)) {
+ continue;
+ }
+ Algorithm wrongPrivate = algorithm(set, null, keys.get(keySet).getPrivate());
+ SignatureGenerationException signing = assertThrows(set + " with " + keySet,
+ SignatureGenerationException.class,
+ () -> JWT.create().withIssuer("auth0").sign(wrongPrivate));
+ assertThat(signing.getCause(), is(instanceOf(InvalidKeyException.class)));
+
+ String token = JWT.create().withIssuer("auth0").sign(algorithm(set));
+ Algorithm wrongPublic = algorithm(set, keys.get(keySet).getPublic(), null);
+ SignatureVerificationException verifying = assertThrows(set + " with " + keySet,
+ SignatureVerificationException.class, () -> wrongPublic.verify(JWT.decode(token)));
+ assertThat(verifying.getCause(), is(instanceOf(InvalidKeyException.class)));
+ }
+ }
+ }
+
+ @Test
+ public void shouldRejectAKeyOfAnotherAlgorithm() {
+ for (String set : SETS) {
+ Algorithm rsaPrivate = algorithm(set, null, rsaKeys.getPrivate());
+ SignatureGenerationException signing = assertThrows(SignatureGenerationException.class,
+ () -> JWT.create().sign(rsaPrivate));
+ assertThat(signing.getCause(), is(instanceOf(InvalidKeyException.class)));
+
+ String token = JWT.create().sign(algorithm(set));
+ Algorithm rsaPublic = algorithm(set, rsaKeys.getPublic(), null);
+ SignatureVerificationException verifying = assertThrows(SignatureVerificationException.class,
+ () -> rsaPublic.verify(JWT.decode(token)));
+ assertThat(verifying.getCause(), is(instanceOf(InvalidKeyException.class)));
+ }
+ }
+
+ @Test
+ public void shouldNotVerifyATokenOfAnotherParameterSet() {
+ String token = JWT.create().withIssuer("auth0").sign(algorithm("ML-DSA-65"));
+ assertThrows(AlgorithmMismatchException.class,
+ () -> JWT.require(algorithm("ML-DSA-44")).build().verify(token));
+ assertThrows(AlgorithmMismatchException.class,
+ () -> JWT.require(Algorithm.RSA256((java.security.interfaces.RSAPublicKey) rsaKeys.getPublic(), null))
+ .build().verify(token));
+ }
+
+ @Test
+ public void shouldNotVerifyAnRsaTokenRelabelledAsMlDsa() {
+ String rsaToken = JWT.create().withIssuer("auth0").sign(Algorithm.RSA256(
+ (java.security.interfaces.RSAPublicKey) rsaKeys.getPublic(),
+ (java.security.interfaces.RSAPrivateKey) rsaKeys.getPrivate()));
+ String[] parts = rsaToken.split("\\.");
+ String header = Base64.getUrlEncoder().withoutPadding()
+ .encodeToString("{\"alg\":\"ML-DSA-44\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
+ String relabelled = header + "." + parts[1] + "." + parts[2];
+ assertThrows(SignatureVerificationException.class,
+ () -> JWT.require(algorithm("ML-DSA-44")).build().verify(relabelled));
+ }
+
+ @Test
+ public void shouldThrowWhenTheKeyProviderIsNull() {
+ assertThrows(IllegalArgumentException.class, () -> Algorithm.MLDSA44((MLDSAKeyProvider) null));
+ assertThrows(IllegalArgumentException.class, () -> Algorithm.MLDSA65((MLDSAKeyProvider) null));
+ assertThrows(IllegalArgumentException.class, () -> Algorithm.MLDSA87((MLDSAKeyProvider) null));
+ assertThrows(IllegalArgumentException.class, () -> Algorithm.MLDSA44(null, null));
+ assertThrows(IllegalArgumentException.class, () -> Algorithm.MLDSA65(null, null));
+ assertThrows(IllegalArgumentException.class, () -> Algorithm.MLDSA87(null, null));
+ }
+
+ @Test
+ public void shouldFailWhenAKeyIsMissing() {
+ for (String set : SETS) {
+ Algorithm verifyOnly = algorithm(set, keys.get(set).getPublic(), null);
+ SignatureGenerationException signing = assertThrows(SignatureGenerationException.class,
+ () -> JWT.create().sign(verifyOnly));
+ assertThat(signing.getCause(), is(instanceOf(IllegalStateException.class)));
+
+ String token = JWT.create().sign(algorithm(set));
+ Algorithm signOnly = algorithm(set, null, keys.get(set).getPrivate());
+ SignatureVerificationException verifying = assertThrows(SignatureVerificationException.class,
+ () -> signOnly.verify(JWT.decode(token)));
+ assertThat(verifying.getCause(), is(instanceOf(IllegalStateException.class)));
+ }
+ }
+
+ @Test
+ public void shouldUseTheKeyProviderAndItsKeyId() {
+ final KeyPair pair = keys.get("ML-DSA-65");
+ MLDSAKeyProvider provider = new MLDSAKeyProvider() {
+ @Override
+ public PublicKey getPublicKeyById(String keyId) {
+ return "my-key".equals(keyId) ? pair.getPublic() : null;
+ }
+
+ @Override
+ public PrivateKey getPrivateKey() {
+ return pair.getPrivate();
+ }
+
+ @Override
+ public String getPrivateKeyId() {
+ return "my-key";
+ }
+ };
+ Algorithm algorithm = Algorithm.MLDSA65(provider);
+ assertThat(algorithm.getSigningKeyId(), is("my-key"));
+ String token = JWT.create().withIssuer("auth0").sign(algorithm);
+ assertThat(JWT.decode(token).getKeyId(), is("my-key"));
+ assertThat(JWT.require(algorithm).build().verify(token), is(notNullValue()));
+
+ String withoutKid = JWT.create().withIssuer("auth0").sign(algorithm("ML-DSA-65"));
+ assertThrows(SignatureVerificationException.class, () -> algorithm.verify(JWT.decode(withoutKid)));
+ }
+
+ @Test
+ public void shouldProduceDifferentTokensForDifferentKeys() {
+ String a = JWT.create().withIssuer("auth0").sign(algorithm("ML-DSA-44"));
+ String b = JWT.create().withIssuer("auth0").sign(
+ algorithm("ML-DSA-44", null, otherKeys.get("ML-DSA-44").getPrivate()));
+ assertThat(a.split("\\.")[2], is(not(b.split("\\.")[2])));
+ }
+
+ @Test
+ public void shouldFailCleanlyWhenNoProviderImplementsMlDsa() {
+ Security.removeProvider(bcProvider.getName());
+ try {
+ boolean nativeSupport = true;
+ try {
+ Signature.getInstance("ML-DSA-65");
+ } catch (NoSuchAlgorithmException e) {
+ nativeSupport = false;
+ }
+ Assume.assumeFalse("this JVM implements ML-DSA itself", nativeSupport);
+
+ SignatureGenerationException e = assertThrows(SignatureGenerationException.class,
+ () -> JWT.create().sign(algorithm("ML-DSA-65")));
+ assertThat(e.getCause(), is(instanceOf(NoSuchAlgorithmException.class)));
+ } finally {
+ Security.insertProviderAt(bcProvider, 1);
+ }
+ }
+}
diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/MLDSAInteropTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/MLDSAInteropTest.java
new file mode 100644
index 00000000..0eb2ad33
--- /dev/null
+++ b/lib/src/test/java/com/auth0/jwt/algorithms/MLDSAInteropTest.java
@@ -0,0 +1,113 @@
+package com.auth0.jwt.algorithms;
+
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.exceptions.SignatureGenerationException;
+import com.auth0.jwt.exceptions.SignatureVerificationException;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThrows;
+
+/**
+ * Two independent ML-DSA implementations must agree on tokens: the JDK's own (Java 24 and later) and BouncyCastle.
+ * BouncyCastle is deliberately not registered here, so the library itself runs on the JDK's implementation.
+ * Skipped on JVMs without native ML-DSA.
+ */
+public class MLDSAInteropTest {
+
+ private static final String[] SETS = {"ML-DSA-44", "ML-DSA-65", "ML-DSA-87"};
+ private final Provider bc = new BouncyCastleProvider();
+
+ @Before
+ public void requireNativeMlDsa() {
+ boolean nativeSupport = true;
+ try {
+ Signature.getInstance("ML-DSA-65");
+ } catch (NoSuchAlgorithmException e) {
+ nativeSupport = false;
+ }
+ Assume.assumeTrue("this JVM has no native ML-DSA", nativeSupport);
+ }
+
+ private static Algorithm algorithm(String set, PublicKey publicKey, PrivateKey privateKey) {
+ switch (set) {
+ case "ML-DSA-44":
+ return Algorithm.MLDSA44(publicKey, privateKey);
+ case "ML-DSA-65":
+ return Algorithm.MLDSA65(publicKey, privateKey);
+ default:
+ return Algorithm.MLDSA87(publicKey, privateKey);
+ }
+ }
+
+ @Test
+ public void tokensSignedOnTheJdkVerifyWithBouncyCastle() throws Exception {
+ for (String set : SETS) {
+ KeyPair jdk = KeyPairGenerator.getInstance(set).generateKeyPair();
+ String token = JWT.create().withIssuer("auth0").sign(algorithm(set, null, jdk.getPrivate()));
+ String[] parts = token.split("\\.");
+
+ PublicKey sameKeyInBc = KeyFactory.getInstance(set, bc)
+ .generatePublic(new X509EncodedKeySpec(jdk.getPublic().getEncoded()));
+ Signature verifier = Signature.getInstance(set, bc);
+ verifier.initVerify(sameKeyInBc);
+ verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8));
+ assertThat(set, verifier.verify(Base64.getUrlDecoder().decode(parts[2])), is(true));
+ }
+ }
+
+ @Test
+ public void tokensSignedWithBouncyCastleVerifyOnTheJdk() throws Exception {
+ for (String set : SETS) {
+ KeyPair bcKeys = KeyPairGenerator.getInstance(set, bc).generateKeyPair();
+ String header = Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(("{\"alg\":\"" + set + "\",\"typ\":\"JWT\"}").getBytes(StandardCharsets.UTF_8));
+ String payload = Base64.getUrlEncoder().withoutPadding()
+ .encodeToString("{\"iss\":\"auth0\"}".getBytes(StandardCharsets.UTF_8));
+ Signature signer = Signature.getInstance(set, bc);
+ signer.initSign(bcKeys.getPrivate());
+ signer.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
+ String token = header + "." + payload + "."
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign());
+
+ PublicKey sameKeyInJdk = KeyFactory.getInstance(set)
+ .generatePublic(new X509EncodedKeySpec(bcKeys.getPublic().getEncoded()));
+ JWT.require(algorithm(set, sameKeyInJdk, null)).withIssuer("auth0").build().verify(token);
+ }
+ }
+
+ @Test
+ public void theJdkRejectsAKeyFromAnotherParameterSet() throws Exception {
+ for (String set : SETS) {
+ for (String keySet : SETS) {
+ if (set.equals(keySet)) {
+ continue;
+ }
+ KeyPair wrong = KeyPairGenerator.getInstance(keySet).generateKeyPair();
+ assertThrows(set + " with " + keySet, SignatureGenerationException.class,
+ () -> JWT.create().sign(algorithm(set, null, wrong.getPrivate())));
+
+ KeyPair right = KeyPairGenerator.getInstance(set).generateKeyPair();
+ String token = JWT.create().sign(algorithm(set, null, right.getPrivate()));
+ assertThrows(set + " with " + keySet, SignatureVerificationException.class,
+ () -> algorithm(set, wrong.getPublic(), null).verify(JWT.decode(token)));
+ }
+ }
+ }
+}