Replace instanceof chain in CryptoAlgorithms.create() with a Java 21 pattern switch
#20
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
The
AUDIT_MODE == WRAPbranch inCryptoAlgorithms.create()dispatches overfive known
CryptoContextsubtypes using a chain ofinstanceofchecks, eachfollowed by an identical
AuditedContexts.wrap(ctx, listener, role)call and a@SuppressWarnings("unchecked")cast. Adding a new context type (e.g. anagreement context, a KDF context) requires a manual edit to this chain; forgetting
to do so silently falls through to the unwrapped
return ctxat the bottom.Why this matters
The current structure scales poorly as new context types are added and provides no
compile-time safety net. Java 21 sealed interfaces combined with pattern-matching
switchallow the compiler to enforce exhaustiveness — a missing case becomes acompile error rather than a silent audit gap.
Proposed change
CryptoContext(or introduce aWrappableCryptoContextsub-interface)as a
sealed interfacepermitting the known concrete subtypes:SignatureContext,EncryptionContext,KemContext,DigestContext,MacContext.instanceofchain with a pattern-matchingswitch:With a sealed hierarchy and no
default, the compiler will flag any futuresubtype that is not explicitly handled, making audit gaps visible at build time.
CryptoContextis not desirable (e.g. to allow third-partyextensions), retain
default -> ctxand document the fallback explicitly.Acceptance criteria
instanceofchain is replaced by aswitchexpression.CryptoContextis sealed: nodefaultbranch; the compiler enforcesexhaustiveness.
CryptoContextremains open:default -> ctxis present and Javadocdocuments that unknown types are returned unwrapped.
@SuppressWarnings("unchecked")casts are confined to the switch arms, notrepeated in an outer block.