001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.jose; 018 019import com.google.errorprone.annotations.CheckReturnValue; 020import com.revetsec.internal.Limits; 021import com.revetsec.internal.crypto.HashAlgorithm; 022import com.revetsec.internal.crypto.EcCurve; 023import com.revetsec.internal.crypto.EcPublicKeys; 024import com.revetsec.internal.crypto.EcdsaSignatures; 025import com.revetsec.internal.crypto.Ed25519PublicKeys; 026import com.revetsec.internal.crypto.KeyRejectedException; 027import com.revetsec.internal.crypto.RsaPublicKeys; 028import com.revetsec.internal.crypto.SignatureVerifier; 029import com.revetsec.internal.crypto.VerifyResult; 030import com.revetsec.internal.encoding.Base64Url; 031import com.revetsec.internal.http.Deadline; 032import com.revetsec.internal.jose.Algorithms; 033import com.revetsec.internal.jose.JwkParser; 034import com.revetsec.internal.json.JsonCodec; 035import com.revetsec.internal.json.JsonLimits; 036import com.revetsec.internal.json.JsonParseException; 037import com.revetsec.json.JsonArray; 038import com.revetsec.json.JsonBoolean; 039import com.revetsec.json.JsonNumber; 040import com.revetsec.json.JsonObject; 041import com.revetsec.json.JsonString; 042import com.revetsec.json.JsonValue; 043import org.jspecify.annotations.NonNull; 044import org.jspecify.annotations.Nullable; 045import javax.annotation.concurrent.Immutable; 046import javax.annotation.concurrent.NotThreadSafe; 047import javax.annotation.concurrent.ThreadSafe; 048import java.math.BigInteger; 049import java.nio.charset.StandardCharsets; 050import java.security.GeneralSecurityException; 051import java.security.PrivateKey; 052import java.security.PublicKey; 053import java.security.Signature; 054import java.security.interfaces.RSAPublicKey; 055import java.security.interfaces.ECPublicKey; 056import java.security.interfaces.EdECKey; 057import java.security.interfaces.EdECPublicKey; 058import java.security.spec.EdECPoint; 059import java.security.spec.NamedParameterSpec; 060import java.security.spec.ECFieldFp; 061import java.security.spec.ECParameterSpec; 062import java.security.spec.ECPoint; 063import java.security.spec.EllipticCurve; 064import java.security.spec.AlgorithmParameterSpec; 065import java.security.spec.MGF1ParameterSpec; 066import java.security.spec.PSSParameterSpec; 067import java.time.Duration; 068import java.util.Arrays; 069import static java.util.Objects.requireNonNull; 070 071/** 072 * Signs compact JWS credentials with one application-owned key pair and one fixed algorithm. 073 * PS256, PS384, PS512, RS256, RS384, RS512, ES256, ES384 and Ed25519 are supported. Each operation uses fresh JCA engines and verifies its actual signature 074 * against the checked public projection before releasing any credential. Provider selection is left to JCA; 075 * no fallback or provider configuration change is made. 076 * <p> 077 * The private key is retained by reference, may be opaque or nonexportable, and is never encoded or returned. 078 * Applications own its persistent storage, registration and rotation. Construction makes structural checks only: 079 * it never signs, probes the pair or invokes a JCA provider. Explicit {@link #warmUp(Duration)} probes the pair 080 * without creating a credential. 081 * <p> 082 * Operations run on the caller thread and measure their remaining budget with monotonic time. They discard late 083 * output but cannot preempt a trusted provider that hangs: bounded completion requires cooperative providers. 084 * Callers also check their original deadline after this operation. No thread or executor is owned by the signer. 085 * 086 * @author <a href="https://www.revetkn.com">Mark Allen</a> 087 * @since 1.0.0 088 */ 089@ThreadSafe 090public final class JwsSigner { 091 private static final @NonNull Duration DEFAULT_REMAINING_BUDGET = Duration.ofSeconds(2); 092 private static final int MAXIMUM_COMPACT_LENGTH = Limits.COMPACT_JWT_SIZE.getDefaultIntValue(); 093 private static final int MAXIMUM_CLAIMS_LENGTH = MAXIMUM_COMPACT_LENGTH / 2; 094 private static final int MAXIMUM_HEADER_LENGTH = MAXIMUM_COMPACT_LENGTH / 16; 095 private static final int CERTIFICATE_DIGEST_LENGTH = 32; 096 private static final String PROBE = "Revetsec RSA signing key pair noncredential probe v1"; 097 private static final @NonNull JsonLimits CLAIM_LIMITS = JsonLimits.jose(MAXIMUM_CLAIMS_LENGTH); 098 099 private final @NonNull PrivateKey privateKey; 100 private final @NonNull PublicKey publicKey; 101 private final int signatureLength; 102 private final @Nullable EcCurve ecCurve; 103 private final @NonNull JwsAlgorithm algorithm; 104 // Ed25519 is a pure JCA operation with no caller-supplied digest/prehash parameter. 105 private final @Nullable HashAlgorithm hash; 106 107 private JwsSigner(@NonNull PrivateKey privateKey, @NonNull PublicProjection publicKey, 108 @NonNull JwsAlgorithm algorithm) { 109 this(privateKey, publicKey, algorithm, publicKey.signatureLength(), null); 110 } 111 112 private JwsSigner(@NonNull PrivateKey privateKey, @NonNull PublicKey publicKey, 113 @NonNull JwsAlgorithm algorithm, int signatureLength, @Nullable EcCurve ecCurve) { 114 this.privateKey = privateKey; 115 this.publicKey = publicKey; 116 this.signatureLength = signatureLength; 117 this.ecCurve = ecCurve; 118 this.algorithm = algorithm; 119 this.hash = Algorithms.findHash(algorithm).orElse(null); 120 } 121 122 /** 123 * Returns a signer after bounded structural checks of its algorithm and inspectable RSA public projection. 124 * Public keys must satisfy the existing 2048–16384-bit, exponent and ROCA policy. RSA-PSS key restrictions are 125 * preserved; a PSS-only key cannot be selected for RS256, RS384 or RS512. This factory does not test pair agreement. 126 * 127 * @param privateKey the application-owned private key, retained by reference without encoding 128 * @param publicKey the inspectable RSA public key, snapshotted without encoding 129 * @param algorithm exactly PS256, PS384, PS512, RS256, RS384 or RS512 130 * @return the signer 131 * @throws NullPointerException if a required argument is null 132 * @throws IllegalArgumentException if a supplied algorithm or key is structurally invalid or unsupported 133 * @since 1.0.0 134 */ 135 @CheckReturnValue 136 public static @NonNull JwsSigner fromRsaKeyPair(@NonNull PrivateKey privateKey, @NonNull PublicKey publicKey, 137 @NonNull JwsAlgorithm algorithm) { 138 requireNonNull(privateKey); 139 requireNonNull(publicKey); 140 requireNonNull(algorithm); 141 if (algorithm != JwsAlgorithm.PS256 && algorithm != JwsAlgorithm.PS384 && algorithm != JwsAlgorithm.PS512 142 && algorithm != JwsAlgorithm.RS256 && algorithm != JwsAlgorithm.RS384 && algorithm != JwsAlgorithm.RS512) 143 throw invalidKey(); 144 try { 145 if (!(publicKey instanceof RSAPublicKey rsaKey)) throw invalidKey(); 146 String privateAlgorithm = requireNonNull(privateKey.getAlgorithm()); 147 String publicAlgorithm = requireNonNull(publicKey.getAlgorithm()); 148 if (!rsaAlgorithm(privateAlgorithm) || !rsaAlgorithm(publicAlgorithm)) throw invalidKey(); 149 @Nullable AlgorithmParameterSpec parameters = rsaKey.getParams(); 150 if (!isRsaPss(algorithm) && (isPss(privateAlgorithm) || isPss(publicAlgorithm) 151 || parameters != null)) throw invalidKey(); 152 PublicProjection projection = new PublicProjection(snapshotInteger(requireNonNull(rsaKey.getModulus()), 16384, 2049), 153 snapshotInteger(requireNonNull(rsaKey.getPublicExponent()), 32, 5), publicAlgorithm, snapshotParameters(parameters, Algorithms.findHash(algorithm).orElseThrow())); 154 RsaPublicKeys.checkPublicKey(projection); 155 return new JwsSigner(privateKey, projection, algorithm); 156 } catch (KeyRejectedException | RuntimeException failure) { 157 throw invalidKey(); 158 } 159 } 160 161 /** 162 * Returns a signer after bounded structural checks of an EC public point and its complete domain parameters. 163 * ES256 requires exactly P-256; ES384 requires exactly P-384. The optional domain seed is not significant. 164 * The private key must report EC and may remain opaque. This factory does not invoke JCA or test pair agreement; 165 * each signing operation verifies its actual signature against the independent public snapshot before release. 166 * 167 * @param privateKey the application-owned EC private key, retained by reference without encoding 168 * @param publicKey the inspectable EC public key, snapshotted without encoding 169 * @param algorithm exactly ES256 or ES384 170 * @return the signer 171 * @throws NullPointerException if a required argument is null 172 * @throws IllegalArgumentException if the algorithm, public point or domain parameters are unsupported or invalid 173 * @since 1.0.0 174 */ 175 @CheckReturnValue 176 public static @NonNull JwsSigner fromEcKeyPair(@NonNull PrivateKey privateKey, @NonNull PublicKey publicKey, 177 @NonNull JwsAlgorithm algorithm) { 178 requireNonNull(privateKey); requireNonNull(publicKey); requireNonNull(algorithm); 179 EcCurve curve = switch (algorithm) { 180 case ES256 -> EcCurve.P_256; 181 case ES384 -> EcCurve.P_384; 182 default -> throw invalidEcKey(); 183 }; 184 try { 185 if (!(publicKey instanceof ECPublicKey ecKey) 186 || !"EC".equalsIgnoreCase(privateKey.getAlgorithm()) 187 || !"EC".equalsIgnoreCase(publicKey.getAlgorithm())) throw invalidEcKey(); 188 ECParameterSpec parameters = snapshotEcParameters(requireNonNull(ecKey.getParams()), curve); 189 if (!curve.isDescribedBy(parameters)) throw invalidEcKey(); 190 ECPoint point = requireNonNull(ecKey.getW()); 191 EcPublicProjection projection = new EcPublicProjection(curve, 192 snapshotEcInteger(requireNonNull(point.getAffineX()), curve), 193 snapshotEcInteger(requireNonNull(point.getAffineY()), curve)); 194 EcPublicKeys.checkPublicKey(curve, projection); 195 return new JwsSigner(privateKey, projection, algorithm, curve.getSignatureLength(), curve); 196 } catch (KeyRejectedException | RuntimeException failure) { throw invalidEcKey(); } 197 } 198 199 /** 200 * Returns a signer for pure Ed25519 with the fully specified {@code Ed25519} JWS algorithm identifier. 201 * The public key must name Ed25519 and its bounded point must decode canonically and not have small order. 202 * Its point and parameters are snapshotted without encoding. The private key may remain opaque and must report 203 * Ed25519 or EdDSA; if it exposes {@link EdECKey} parameters, those must name Ed25519. Private key bytes are never 204 * read. Construction invokes no JCA provider or signing probe; every actual operation verifies 205 * its signature against the checked public snapshot before release. Legacy {@code EdDSA} is not emitted. 206 * 207 * @param privateKey the application-owned private key, retained by reference without encoding 208 * @param publicKey the inspectable Ed25519 public key, snapshotted without encoding 209 * @return the signer using {@link JwsAlgorithm#ED25519} 210 * @throws NullPointerException if a required argument is null 211 * @throws IllegalArgumentException if a supplied key or inspectable parameter is structurally invalid or unsupported 212 * @since 1.0.0 213 */ 214 @CheckReturnValue 215 public static @NonNull JwsSigner fromEd25519KeyPair(@NonNull PrivateKey privateKey, @NonNull PublicKey publicKey) { 216 requireNonNull(privateKey); requireNonNull(publicKey); 217 try { 218 if (!(publicKey instanceof EdECPublicKey edKey) || !ed25519Algorithm(privateKey.getAlgorithm()) 219 || !ed25519Algorithm(publicKey.getAlgorithm())) throw invalidEd25519Key(); 220 if (privateKey instanceof EdECKey inspectable 221 && !"Ed25519".equals(requireNonNull(inspectable.getParams()).getName())) throw invalidEd25519Key(); 222 if (!"Ed25519".equals(requireNonNull(edKey.getParams()).getName())) throw invalidEd25519Key(); 223 EdECPoint point = requireNonNull(edKey.getPoint()); 224 Ed25519PublicProjection projection = new Ed25519PublicProjection(snapshotEd25519Y(requireNonNull(point.getY())), 225 point.isXOdd()); 226 Ed25519PublicKeys.checkPublicKey(projection); 227 return new JwsSigner(privateKey, projection, JwsAlgorithm.ED25519, Ed25519PublicKeys.SIGNATURE_LENGTH, null); 228 } catch (KeyRejectedException | RuntimeException failure) { throw invalidEd25519Key(); } 229 } 230 231 /** 232 * Returns the one selected signing algorithm. 233 * @return the selected signing algorithm 234 * @since 1.0.0 235 */ 236 public @NonNull JwsAlgorithm getAlgorithm() { return this.algorithm; } 237 238 /** 239 * Returns the stable, inspectable checked public projection. It does not expose private material, and its 240 * encoding and format are absent; applications retain their original public key when an encoded key is needed. 241 * @return the checked public key 242 * @since 1.0.0 243 */ 244 public @NonNull PublicKey getPublicKey() { return this.publicKey; } 245 246 /** 247 * Starts a signing builder with the required protected-header metadata and outbound claims. Construction does 248 * not serialize claims or invoke a provider. The builder's {@link Builder#build()} signs and returns a compact 249 * JWT, using a two-second operation budget unless overridden. The algorithm always comes from this signer. 250 * 251 * @param header the required header metadata 252 * @param claims the required outbound claims; construction does not establish that they are trusted or valid 253 * @return a new signing builder 254 * @throws NullPointerException if a required argument is null 255 * @since 1.0.0 256 */ 257 @CheckReturnValue 258 public @NonNull Builder withHeaderAndClaims(@NonNull JwtSigningHeader header, @NonNull JwtClaimsSet claims) { 259 return new Builder(this, header, claims); 260 } 261 262 /** 263 * Signs the header metadata and outbound claims with the default two-second operation budget, returning a 264 * compact JWT credential. Equivalent to {@code withHeaderAndClaims(header, claims).build()}. The algorithm 265 * comes from this signer, and the claims' application meaning remains the caller's responsibility. 266 * 267 * @param header the required header metadata 268 * @param claims the required outbound claims 269 * @return the verified compact JWT credential; keep it out of logs 270 * @throws NullPointerException if a required argument is null 271 * @throws IllegalArgumentException if the serialized claims exceed the signing JSON profile or size limits 272 * @throws JwsSigningException if signing, pair verification or the operation budget fails 273 * @since 1.0.0 274 */ 275 @CheckReturnValue 276 public @NonNull String fromHeaderAndClaims(@NonNull JwtSigningHeader header, @NonNull JwtClaimsSet claims) { 277 return withHeaderAndClaims(header, claims).build(); 278 } 279 280 /** 281 * Signs the exact accepted UTF-8 claims bytes and returns a compact JWS credential, an explicit secret emission. 282 * Claims are one strict JSON object under the existing JOSE defaults, limited to 32 KiB; their semantics belong 283 * to the caller. Arrays are snapshotted after length checks. The fixed protected header holds only alg, typ and 284 * optional kid/x5t#S256, is limited to 4 KiB encoded, and the final compact credential to 64 KiB. 285 * 286 * @param type exactly client-authentication+jwt, JWT or at+jwt 287 * @param keyId a nonempty key identifier of at most 256 characters, or null for none 288 * @param certificateSha256Thumbprint exactly 32 bytes, SHA-256 of a DER certificate, or null for none 289 * @param claimsUtf8 strict UTF-8 JSON object bytes; the accepted bytes are signed without reserialization 290 * @param remainingBudget the caller's remaining monotonic budget; nonpositive values are exhausted 291 * @return the verified compact JWS credential; keep it out of logs 292 * @throws NullPointerException if a required argument is null 293 * @throws IllegalArgumentException if a supplied type, identifier, digest or claims input is invalid 294 * @throws JwsSigningException if signing, pair verification or the remaining budget fails 295 * @since 1.0.0 296 */ 297 @CheckReturnValue 298 public @NonNull String toCompactSerialization(@NonNull String type, @Nullable String keyId, 299 byte @Nullable [] certificateSha256Thumbprint, byte @NonNull [] claimsUtf8, 300 @NonNull Duration remainingBudget) { 301 requireNonNull(type); 302 requireNonNull(claimsUtf8); 303 requireNonNull(remainingBudget); 304 return toCompactSerialization(type, keyId, certificateSha256Thumbprint, claimsUtf8, deadline(remainingBudget)); 305 } 306 307 private @NonNull String toCompactSerialization(@NonNull String type, @Nullable String keyId, 308 byte @Nullable [] certificateSha256Thumbprint, byte @NonNull [] claimsUtf8, @NonNull Deadline deadline) { 309 if (!(type.equals("client-authentication+jwt") || type.equals("JWT") || type.equals("at+jwt"))) 310 throw invalidInput(); 311 if (keyId != null && (keyId.isEmpty() || keyId.length() > JwkParser.MAXIMUM_KEY_ID_LENGTH)) 312 throw invalidInput(); 313 if (certificateSha256Thumbprint != null && certificateSha256Thumbprint.length != CERTIFICATE_DIGEST_LENGTH) 314 throw invalidInput(); 315 if (claimsUtf8.length > MAXIMUM_CLAIMS_LENGTH) throw invalidInput(); 316 byte[] claims = claimsUtf8.clone(); 317 byte @Nullable [] digest = certificateSha256Thumbprint == null ? null : certificateSha256Thumbprint.clone(); 318 byte @Nullable [] header = null; 319 byte @Nullable [] input = null; 320 byte @Nullable [] signature = null; 321 try { 322 checkBudget(deadline); 323 try { 324 if (!(JsonCodec.parse(claims, CLAIM_LIMITS) instanceof JsonObject)) throw invalidInput(); 325 } catch (JsonParseException failure) { throw invalidInput(); } 326 checkBudget(deadline); 327 String wireAlgorithm = this.algorithm.getWireValue(); 328 @Nullable String thumbprint = digest == null ? null : Base64Url.encode(digest); 329 long headerBytes = 15L + jsonStringBytes(wireAlgorithm) + jsonStringBytes(type); 330 if (keyId != null) headerBytes += 7L + jsonStringBytes(keyId); 331 if (thumbprint != null) headerBytes += 12L + jsonStringBytes(thumbprint); 332 if (encodedLength(headerBytes) > MAXIMUM_HEADER_LENGTH) throw invalidInput(); 333 JsonObject.Builder builder = JsonObject.builder().put("alg", wireAlgorithm).put("typ", type); 334 if (keyId != null) builder.put("kid", keyId); 335 if (thumbprint != null) builder.put("x5t#S256", thumbprint); 336 header = JsonCodec.toUtf8Bytes(builder.build()); 337 long headerLength = encodedLength(header.length); 338 long claimsLength = encodedLength(claims.length); 339 if (headerLength > MAXIMUM_HEADER_LENGTH || headerLength + claimsLength + 2L 340 + encodedLength(this.signatureLength) > MAXIMUM_COMPACT_LENGTH) throw invalidInput(); 341 checkBudget(deadline); 342 String signingInput = Base64Url.encode(header) + "." + Base64Url.encode(claims); 343 input = signingInput.getBytes(StandardCharsets.US_ASCII); 344 signature = signAndVerify(input, deadline); 345 String compact = signingInput + "." + Base64Url.encode(signature); 346 if (compact.length() > MAXIMUM_COMPACT_LENGTH) throw invalidInput(); 347 checkBudget(deadline); 348 return compact; 349 } finally { 350 Arrays.fill(claims, (byte) 0); 351 clear(digest); clear(header); clear(input); clear(signature); 352 } 353 } 354 355 /** 356 * Explicitly signs and verifies a fixed internal noncredential probe without returning a credential. 357 * It runs on the caller thread; trusted providers must cooperate with the budget (see the class description). 358 * @param remainingBudget the caller's remaining monotonic budget 359 * @throws NullPointerException if remainingBudget is null 360 * @throws JwsSigningException if signing, pair verification or the budget fails 361 * @since 1.0.0 362 */ 363 public void warmUp(@NonNull Duration remainingBudget) { 364 Deadline deadline = deadline(requireNonNull(remainingBudget)); 365 byte[] input = PROBE.getBytes(StandardCharsets.US_ASCII); 366 byte @Nullable [] signature = null; 367 try { signature = signAndVerify(input, deadline); checkBudget(deadline); } 368 finally { clear(input); clear(signature); } 369 } 370 371 /** 372 * Returns a description without key or credential contents. 373 * @return the redacted description 374 * @since 1.0.0 375 */ 376 @Override 377 public @NonNull String toString() { return "JwsSigner{key=<redacted>}"; } 378 379 /** 380 * Configures one signing operation. Header and claims are immutable snapshots; the builder owns no credential. 381 * Each {@link #build()} starts a fresh budget, serializes the claims and signs on the caller thread. A trusted 382 * JCA provider must cooperate with the budget; it cannot be forcibly interrupted. Callers enforcing an original 383 * deadline must also recheck it after the operation. 384 * 385 * @author <a href="https://www.revetkn.com">Mark Allen</a> 386 * @since 1.0.0 387 */ 388 @NotThreadSafe 389 @CheckReturnValue 390 public static final class Builder { 391 private final @NonNull JwsSigner signer; 392 private final @NonNull JwtSigningHeader header; 393 private final @NonNull JwtClaimsSet claims; 394 private @NonNull Duration remainingBudget = DEFAULT_REMAINING_BUDGET; 395 396 private Builder(@NonNull JwsSigner signer, @NonNull JwtSigningHeader header, @NonNull JwtClaimsSet claims) { 397 this.signer = requireNonNull(signer); 398 this.header = requireNonNull(header); 399 this.claims = requireNonNull(claims); 400 } 401 402 /** 403 * Sets the budget measured from entry to {@link #build()}, including claims serialization and signing. 404 * Nonpositive values are exhausted and cause {@code build()} to fail without signing. 405 * 406 * @param remainingBudget the remaining operation allowance, or null to restore the two-second default 407 * @return this builder 408 * @since 1.0.0 409 */ 410 public @NonNull Builder remainingBudget(@Nullable Duration remainingBudget) { 411 this.remainingBudget = remainingBudget == null ? DEFAULT_REMAINING_BUDGET : remainingBudget; 412 return this; 413 } 414 415 /** 416 * Serializes the outbound claims, signs them and verifies the signature before returning the compact JWT. 417 * This is an explicit credential emission; it does not validate the application meaning of the claims. 418 * 419 * @return the verified compact JWT credential; keep it out of logs 420 * @throws IllegalArgumentException if the claims exceed the signing JSON profile or size limits 421 * @throws JwsSigningException if signing, pair verification or the operation budget fails 422 * @since 1.0.0 423 */ 424 public @NonNull String build() { 425 Deadline deadline = deadline(this.remainingBudget); 426 JsonObject json = this.claims.toJsonObject(); 427 // Bound the expanded tree before the general JSON writer allocates its output. Shared subtrees can 428 // otherwise expand exponentially despite the immutable JSON model's depth limit. 429 claimsLength(json, deadline); 430 byte[] claimsUtf8 = JsonCodec.toUtf8Bytes(json); 431 byte @Nullable [] digest = this.header.getCertificateSha256Thumbprint().orElse(null); 432 try { 433 checkBudget(deadline); 434 return this.signer.toCompactSerialization(this.header.getType().getWireValue(), 435 this.header.getKeyId().orElse(null), digest, claimsUtf8, deadline); 436 } finally { clear(claimsUtf8); clear(digest); } 437 } 438 439 /** 440 * Returns a description without the header, claims, key or credential. 441 * @return the redacted description 442 * @since 1.0.0 443 */ 444 @Override 445 public @NonNull String toString() { return "JwsSigner.Builder{input=<redacted>}"; } 446 } 447 448 private static int claimsLength(@NonNull JsonValue value, @NonNull Deadline deadline) { 449 checkBudget(deadline); 450 int length; 451 if (value instanceof JsonObject object) { 452 length = 2; 453 boolean first = true; 454 for (var member : object.getMembers().entrySet()) { 455 length = addClaimsLength(length, claimsStringLength(member.getKey()) + (first ? 1 : 2)); 456 length = addClaimsLength(length, claimsLength(member.getValue(), deadline)); 457 first = false; 458 } 459 } else if (value instanceof JsonArray array) { 460 length = 2; 461 boolean first = true; 462 for (JsonValue element : array.getElements()) { 463 length = addClaimsLength(length, (first ? 0 : 1) + claimsLength(element, deadline)); 464 first = false; 465 } 466 } else if (value instanceof JsonString string) length = claimsStringLength(string.getValue()); 467 else if (value instanceof JsonNumber number) length = number.getValue().toString().length(); 468 else if (value instanceof JsonBoolean bool) length = bool.getValue() ? 4 : 5; 469 else length = 4; 470 return addClaimsLength(0, length); 471 } 472 473 private static int claimsStringLength(@NonNull String value) { 474 if (value.length() > MAXIMUM_CLAIMS_LENGTH) throw invalidInput(); 475 return jsonStringBytes(value); 476 } 477 478 private static int addClaimsLength(int length, int additional) { 479 if (additional > MAXIMUM_CLAIMS_LENGTH - length) throw invalidInput(); 480 return length + additional; 481 } 482 483 private byte @NonNull [] signAndVerify(byte @NonNull [] input, @NonNull Deadline deadline) { 484 checkBudget(deadline); 485 byte[] signature; 486 try { 487 Signature engine = Signature.getInstance(this.algorithm == JwsAlgorithm.ED25519 ? "Ed25519" 488 : this.ecCurve != null ? hash().getEcdsaSignatureName() 489 : isRsaPss(this.algorithm) ? "RSASSA-PSS" : hash().getRsaSignatureName()); 490 engine.initSign(this.privateKey); 491 checkBudget(deadline); 492 if (isRsaPss(this.algorithm)) engine.setParameter(hash().getPssParameterSpec()); 493 checkBudget(deadline); 494 engine.update(input); 495 checkBudget(deadline); 496 signature = requireNonNull(engine.sign()); 497 if (this.ecCurve != null) { 498 byte[] der = signature; 499 try { 500 checkBudget(deadline); 501 signature = EcdsaSignatures.toJose(this.ecCurve, der); 502 } finally { clear(der); } 503 } 504 } catch (GeneralSecurityException | RuntimeException failure) { 505 checkBudget(deadline); 506 throw JwsSigningException.fromReason(JwsSigningException.Reason.SIGNING_UNAVAILABLE); 507 } 508 try { 509 checkBudget(deadline); 510 VerifyResult result = this.algorithm == JwsAlgorithm.ED25519 511 ? SignatureVerifier.verifyEd25519(this.publicKey, input, signature) 512 : this.ecCurve != null 513 ? SignatureVerifier.verifyEcdsa(this.ecCurve, hash(), this.publicKey, input, signature) 514 : isRsaPss(this.algorithm) ? SignatureVerifier.verifyRsaPss(hash(), this.publicKey, input, signature) 515 : SignatureVerifier.verifyRsaPkcs1(hash(), this.publicKey, input, signature); 516 checkBudget(deadline); 517 if (result != VerifyResult.VALID) 518 throw JwsSigningException.fromReason(result == VerifyResult.MISMATCH 519 ? JwsSigningException.Reason.KEY_PAIR_MISMATCH : JwsSigningException.Reason.SIGNING_UNAVAILABLE); 520 return signature; 521 } catch (RuntimeException | Error failure) { 522 clear(signature); 523 throw failure; 524 } 525 } 526 527 private @NonNull HashAlgorithm hash() { return requireNonNull(this.hash); } 528 529 private static boolean ed25519Algorithm(@Nullable String algorithm) { 530 return "Ed25519".equalsIgnoreCase(algorithm) || "EdDSA".equalsIgnoreCase(algorithm); 531 } 532 533 private static @NonNull BigInteger snapshotEd25519Y(@NonNull BigInteger value) { 534 if (value.bitLength() < 0 || value.bitLength() > 255) throw invalidEd25519Key(); 535 byte[] bytes = value.toByteArray(); 536 if (bytes.length == 0 || bytes.length > Ed25519PublicKeys.KEY_LENGTH) throw invalidEd25519Key(); 537 BigInteger snapshot = new BigInteger(bytes); 538 if (snapshot.signum() < 0 || snapshot.bitLength() > 255) throw invalidEd25519Key(); 539 return snapshot; 540 } 541 542 private static @NonNull Deadline deadline(@NonNull Duration remainingBudget) { 543 if (remainingBudget.isNegative() || remainingBudget.isZero()) 544 throw JwsSigningException.fromReason(JwsSigningException.Reason.BUDGET_EXHAUSTED); 545 return Deadline.fromNow(remainingBudget); 546 } 547 548 private static void checkBudget(@NonNull Deadline deadline) { 549 if (deadline.isExpired()) throw JwsSigningException.fromReason(JwsSigningException.Reason.BUDGET_EXHAUSTED); 550 } 551 552 private static boolean rsaAlgorithm(@NonNull String algorithm) { 553 return algorithm.equalsIgnoreCase("RSA") || isPss(algorithm); 554 } 555 556 private static boolean isPss(@NonNull String algorithm) { return algorithm.equalsIgnoreCase("RSASSA-PSS"); } 557 558 private static @NonNull BigInteger snapshotInteger(@NonNull BigInteger value, int maximumBits, int maximumBytes) { 559 if (value.bitLength() < 1 || value.bitLength() > maximumBits) throw invalidKey(); 560 byte[] bytes = value.toByteArray(); 561 if (bytes.length == 0 || bytes.length > maximumBytes) throw invalidKey(); 562 return new BigInteger(bytes); 563 } 564 565 private static @NonNull ECParameterSpec snapshotEcParameters(@NonNull ECParameterSpec parameters, 566 @NonNull EcCurve curve) { 567 EllipticCurve domain = requireNonNull(parameters.getCurve()); 568 if (!(domain.getField() instanceof ECFieldFp field)) throw invalidEcKey(); 569 ECPoint generator = requireNonNull(parameters.getGenerator()); 570 return new ECParameterSpec(new EllipticCurve(new ECFieldFp(snapshotEcInteger(field.getP(), curve)), 571 snapshotEcInteger(domain.getA(), curve), snapshotEcInteger(domain.getB(), curve)), 572 new ECPoint(snapshotEcInteger(requireNonNull(generator.getAffineX()), curve), 573 snapshotEcInteger(requireNonNull(generator.getAffineY()), curve)), 574 snapshotEcInteger(parameters.getOrder(), curve), parameters.getCofactor()); 575 } 576 577 private static @NonNull BigInteger snapshotEcInteger(@NonNull BigInteger value, @NonNull EcCurve curve) { 578 int bits = curve.getCoordinateLength() * Byte.SIZE; 579 if (value.bitLength() < 0 || value.bitLength() > bits) throw invalidEcKey(); 580 byte[] bytes = value.toByteArray(); 581 if (bytes.length == 0 || bytes.length > curve.getCoordinateLength() + 1) throw invalidEcKey(); 582 BigInteger snapshot = new BigInteger(bytes); 583 if (snapshot.signum() < 0 || snapshot.bitLength() > bits) throw invalidEcKey(); 584 return snapshot; 585 } 586 587 private static boolean isRsaPss(@NonNull JwsAlgorithm algorithm) { 588 return algorithm == JwsAlgorithm.PS256 || algorithm == JwsAlgorithm.PS384 || algorithm == JwsAlgorithm.PS512; 589 } 590 591 private static @Nullable PSSParameterSpec snapshotParameters(@Nullable AlgorithmParameterSpec parameters, 592 @NonNull HashAlgorithm hash) { 593 if (parameters == null) return null; 594 if (!(parameters instanceof PSSParameterSpec pss) || !(pss.getMGFParameters() instanceof MGF1ParameterSpec mgf)) 595 throw invalidKey(); 596 // Public restrictions must permit this fixed JWS digest/MGF1 pair and digest-sized salt. Private-provider 597 // restrictions remain provider-owned and must succeed with those exact parameters during each operation. 598 if (!pss.getDigestAlgorithm().equalsIgnoreCase(hash.getDigestName()) || !pss.getMGFAlgorithm().equalsIgnoreCase("MGF1") 599 || !mgf.getDigestAlgorithm().equalsIgnoreCase(hash.getDigestName())) throw invalidKey(); 600 int saltLength = pss.getSaltLength(); 601 if (saltLength < 0 || saltLength > hash.getLength() || pss.getTrailerField() != 1) throw invalidKey(); 602 return new PSSParameterSpec(hash.getDigestName(), "MGF1", new MGF1ParameterSpec(hash.getDigestName()), saltLength, 1); 603 } 604 605 private static long encodedLength(long bytes) { return 4L * (bytes / 3L) + (bytes % 3L == 0 ? 0 : bytes % 3L + 1L); } 606 607 private static int jsonStringBytes(@NonNull String value) { 608 int bytes = 2; 609 for (int index = 0; index < value.length(); ++index) { 610 char character = value.charAt(index); 611 if (character == '"' || character == '\\' || character == '\b' || character == '\f' 612 || character == '\n' || character == '\r' || character == '\t') bytes += 2; 613 else if (character < 0x20) bytes += 6; 614 else if (character < 0x80) ++bytes; 615 else if (character < 0x800) bytes += 2; 616 else if (Character.isHighSurrogate(character)) { 617 if (++index >= value.length() || !Character.isLowSurrogate(value.charAt(index))) throw invalidInput(); 618 bytes += 4; 619 } else if (Character.isLowSurrogate(character)) throw invalidInput(); 620 else bytes += 3; 621 } 622 return bytes; 623 } 624 625 private static void clear(byte @Nullable [] bytes) { if (bytes != null) Arrays.fill(bytes, (byte) 0); } 626 private static @NonNull IllegalArgumentException invalidKey() { 627 return new IllegalArgumentException("The RSA signing key or algorithm is invalid."); 628 } 629 private static @NonNull IllegalArgumentException invalidEcKey() { 630 return new IllegalArgumentException("The EC signing key or algorithm is invalid."); 631 } 632 private static @NonNull IllegalArgumentException invalidEd25519Key() { 633 return new IllegalArgumentException("The Ed25519 signing key is invalid."); 634 } 635 private static @NonNull IllegalArgumentException invalidInput() { 636 return new IllegalArgumentException("The JWS signing input is invalid."); 637 } 638 639 @Immutable 640 private static final class Ed25519PublicProjection implements EdECPublicKey { 641 private static final long serialVersionUID = 1L; 642 private final @NonNull BigInteger y; 643 private final boolean xOdd; 644 private Ed25519PublicProjection(@NonNull BigInteger y, boolean xOdd) { this.y = y; this.xOdd = xOdd; } 645 @Override public @NonNull EdECPoint getPoint() { return new EdECPoint(this.xOdd, this.y); } 646 @Override public @NonNull NamedParameterSpec getParams() { return new NamedParameterSpec("Ed25519"); } 647 @Override public @NonNull String getAlgorithm() { return "Ed25519"; } 648 @Override public @Nullable String getFormat() { return null; } 649 @Override public byte @Nullable [] getEncoded() { return null; } 650 @Override public @NonNull String toString() { return "Ed25519PublicKey{material=<redacted>}"; } 651 } 652 653 @Immutable 654 private static final class EcPublicProjection implements ECPublicKey { 655 private static final long serialVersionUID = 1L; 656 private final @NonNull EcCurve curve; 657 private final @NonNull BigInteger x; 658 private final @NonNull BigInteger y; 659 private EcPublicProjection(@NonNull EcCurve curve, @NonNull BigInteger x, @NonNull BigInteger y) { 660 this.curve = curve; this.x = x; this.y = y; 661 } 662 @Override public @NonNull ECPoint getW() { return new ECPoint(this.x, this.y); } 663 @Override public @NonNull ECParameterSpec getParams() { return this.curve.getParameterSpec(); } 664 @Override public @NonNull String getAlgorithm() { return "EC"; } 665 @Override public @Nullable String getFormat() { return null; } 666 @Override public byte @Nullable [] getEncoded() { return null; } 667 @Override public @NonNull String toString() { return "EcPublicKey{material=<redacted>}"; } 668 } 669 670 @Immutable 671 private static final class PublicProjection implements RSAPublicKey { 672 private static final long serialVersionUID = 1L; 673 private final @NonNull BigInteger modulus; 674 private final @NonNull BigInteger exponent; 675 private final @NonNull String algorithm; 676 // Canonical PSS facts retain restrictions even when the inherited RSA key serialization contract is used. 677 private final boolean hasPssParameters; 678 private final int minimumSaltLength; 679 private final @NonNull String pssDigestName; 680 private PublicProjection(@NonNull BigInteger modulus, @NonNull BigInteger exponent, @NonNull String algorithm, 681 @Nullable PSSParameterSpec parameters) { 682 this.modulus = modulus; this.exponent = exponent; this.algorithm = algorithm; 683 this.hasPssParameters = parameters != null; 684 this.minimumSaltLength = parameters == null ? 0 : parameters.getSaltLength(); 685 this.pssDigestName = parameters == null ? "SHA-256" : parameters.getDigestAlgorithm(); 686 } 687 private int signatureLength() { return (this.modulus.bitLength() + 7) / 8; } 688 @Override public @NonNull BigInteger getModulus() { return this.modulus; } 689 @Override public @NonNull BigInteger getPublicExponent() { return this.exponent; } 690 @Override public @NonNull String getAlgorithm() { return this.algorithm; } 691 @Override public @Nullable AlgorithmParameterSpec getParams() { 692 return this.hasPssParameters ? new PSSParameterSpec(this.pssDigestName, "MGF1", new MGF1ParameterSpec(this.pssDigestName), 693 this.minimumSaltLength, 1) : null; 694 } 695 @Override public @Nullable String getFormat() { return null; } 696 @Override public byte @Nullable [] getEncoded() { return null; } 697 @Override public @NonNull String toString() { return "RsaPublicKey{material=<redacted>}"; } 698 } 699}