Crypto Service SDK for Java
A thin, typed Java client for the Crypto Service REST API: hashing, MACs, key derivation, AEAD, server-held Ed25519 and post-quantum keys, HPKE and KMS, all performed by crypto-server.
Contents¶
Getting started
- Install: Maven Central (
co.crypto-service:crypto-service-sdk), Gradle, or from source - Requirements: toolchain floor, the server
- Quick Start: a digest, then a signature with a server-held key
The Crypto Service ecosystem
- The Crypto Service ecosystem: crypto-server, its sibling SDKs and the shared conformance kit
Library reference
- Capabilities at a glance: the current surface by theme
- Ecosystem comparison: short matrix; full table at
docs/COMPARISON.md - Benchmarks: the scenarios; method at
docs/BENCHMARKS.md - Features: async and blocking calls, types, errors, retries
- Configuration: base URL, credentials, timeouts, retries, tracing
- Examples: runnable example index
Operational
- When not to use Crypto Service: limitations
- Development: make targets, fuzzing, CI
- Security: guarantees and reporting
- Documentation: all reference docs
- Stability guarantees: versioning, the breaking axis, toolchain discipline
- License
Install¶
As a Java library¶
<dependency>
<groupId>co.crypto-service</groupId>
<artifactId>crypto-service-sdk</artifactId>
<version>0.0.41</version>
</dependency>
Gradle (Kotlin DSL):
implementation("co.crypto-service:crypto-service-sdk:0.0.41")
The snippets name 0.0.41, the version main prepares; until it is
published, use 0.0.40. 0.0.40, the first version, is on
Maven Central;
versions move in lockstep with the crypto-service suite. Each release
is signed with GPG (key 278D6076E275022D05B70A3FDED76FC6E4ADC8B4),
ships a CycloneDX SBOM and SHA256SUMS on its GitHub release, carries a
build provenance attestation, and can be rebuilt bit for bit from its
tag (docs/packaging.md,
docs/REPRODUCING.md). The JPMS module name is
co.cryptoservice.sdk.
From a clone, build and test it into target/:
make check
The one runtime dependency is Jackson databind
(com.fasterxml.jackson.core:jackson-databind).
Requirements¶
- Java 17 or newer; CI builds and tests on Temurin 17 and 21 on Linux (toolchain policy).
- Maven 3.9.0 or newer to build from source (
./mvnwbrings 3.10.1). - A running crypto-server (
@sebastienrousseau/crypto-server) to call. This SDK is a client: every cryptographic operation happens in the server. CI tests against the crypto-service commit pinned inci/server.ref.
Quick Start¶
import co.cryptoservice.sdk.CryptoServiceClient;
import co.cryptoservice.sdk.HashAlgorithm;
import co.cryptoservice.sdk.HashRequest;
import co.cryptoservice.sdk.KeyGenerateResult;
import co.cryptoservice.sdk.KeyIdRequest;
import co.cryptoservice.sdk.SignRequest;
import co.cryptoservice.sdk.SignResult;
import co.cryptoservice.sdk.VerifyRequest;
public final class QuickStart {
private QuickStart() {}
public static void main(String[] args) {
try (CryptoServiceClient client = CryptoServiceClient.builder()
.baseUrl(System.getenv().getOrDefault("CRYPTO_SERVICE_URL", "http://127.0.0.1:3101"))
.apiKey(System.getenv("CRYPTO_SERVICE_API_KEY"))
.build()) {
System.out.println(client.hash(new HashRequest(HashAlgorithm.SHA256, "abc")).digest());
KeyGenerateResult key = client.generateKeyPair(); // Ed25519, held by the server
SignResult signed = client.sign(new SignRequest(key.keyId(), "hello"));
boolean valid = client.verify(
new VerifyRequest(key.publicKey(), "hello", signed.signature())).valid();
System.out.println("signature valid: " + valid);
client.deleteKey(new KeyIdRequest(key.keyId()));
}
}
}
Start the server first (see DEVELOPMENT.md). hash
posts to /v2/hash and returns the digest as lowercase hex, with
digestBytes() for the bytes. generateKeyPair keeps the private key
on the server and returns its keyId; sign takes that keyId, so the
private key never reaches the client. A rejection raises ApiError with
the server's RFC 9457 problem.
The Crypto Service ecosystem¶
Crypto Service has one engine, crypto-server, and thin typed clients per
language. Every SDK vendors the same conformance kit from crypto-service
(conformance/) and runs every vector through its own client in CI, so
the clients agree on what the server does.
| Component | Purpose | Use case |
|---|---|---|
crypto-service |
The engine: 18 npm packages, among them crypto-server (the REST API this SDK calls), crypto-lib, the TypeScript SDK, the CLI, KMS adapters and the CBOM tooling | Running the service, or calling it from Node.js |
crypto-service-sdk-java |
Typed Java client for the REST API | JVM services that need cryptography without holding keys |
crypto-service-sdk-go, -rust, -python, -dotnet, -cpp |
Typed clients for the same API, proven by the same kit | Services in those languages |
| crypto-service.co | The project site | Documentation and news |
Capabilities at a glance¶
| Area | Capability | Status |
|---|---|---|
| Probes and metadata | health(), live(), ready(), serviceInfo(), algorithms() |
Supported |
| Compliance | getCbom() (CycloneDX 1.6 CBOM), getDoraCompliance() (DORA self-assessment) |
Supported |
| Symmetric | encrypt/decrypt (XChaCha20-Poly1305), secretboxSeal/Open, passwordEncrypt/Decrypt, keyWrap/keyUnwrap (AES-KW, AES-KWP) |
Supported |
| Hashing and KDF | hash, mac, macVerify, kdf (HKDF, PBKDF2, scrypt), passwordHash/Verify (Argon2id) |
Supported |
| Server-held keys | generateKeyPair, exportKey, deleteKey, sign, verify, streamSign, streamVerify |
Supported |
| Public-key encryption | sealedboxSeal/Open, sealedboxSealPq/OpenPq, multiRecipientEncrypt, hpkeGenerateKeyPair/Seal/Open |
Supported |
| Post-quantum | ML-KEM (mlKem...), hybrid X25519 + ML-KEM (pqGenerateKeyPair, pqEncapsulate, pqDecapsulate), ML-DSA (pqSign...), SLH-DSA (pqHashSign...), PQ streams, ISO 20022 dual signatures |
Supported |
| KMS and OPAQUE | kmsCreateKey, kmsWrap/Unwrap, kmsGenerateDataKey, kmsEncrypt/Decrypt; opaqueRegisterInit/Finish, opaqueLoginInit/Finish |
Supported |
| Raw calls | request(method, path, body, contentType): any route, any status |
Supported |
Deprecated v1 routes, /metrics |
Not typed (v1 is sunset on 2027-01-01) | Reachable through request only |
Every operation has an async form (xxxAsync, a CompletableFuture)
and a blocking form (xxx).
Ecosystem comparison¶
The six SDKs share one method surface and one resilience contract, and run crypto-service's conformance kit against a live crypto-server in CI.
| Project | Language (minimum) | Conformance kit in CI | Async model |
|---|---|---|---|
crypto-service crypto-sdk |
TypeScript (Node.js) | In crypto-service's own tests | Promises |
| crypto-service-sdk-java | Java 17 | Yes | CompletableFuture |
| crypto-service-sdk-go, -rust, -python, -dotnet, -cpp | See each repository | Yes | Native to each language |
| Raw HTTP | Any | No | None |
See docs/COMPARISON.md for the complete matrix.
Benchmarks¶
JMH measures four scenarios whose names are the same in every Crypto
Service SDK: encode_request, decode_response and decode_problem
(the client's own cost, no network) and round_trip_hash (a blocking
hash against crypto-server on loopback, run only when
CRYPTO_SERVICE_URL is set). No numbers are published yet;
docs/BENCHMARKS.md describes the method and will
carry generated results.
Features¶
- Async first, blocking when you want it. Each operation returns a
CompletableFuture; its blocking twin waits for it. Cancelling the future (cancel(true)) aborts the HTTP exchange and any pending retry. - One client, thread-safe.
CryptoServiceClientholds one pooledjava.net.http.HttpClient(HTTP/2 where offered, keep-alive) and is safe to share across threads. Blocking calls park inCompletableFuture.get(), so they suit virtual threads. - Typed requests and results as records, with the API's encodings
kept as strings (hex keys and signatures, base64 ciphertexts, UTF-8
text) and
...Bytes()accessors that decode exactly the encoding the OpenAPI schema names;Bytesencodes and decodes for requests. - Errors carry the server's problem. A status outside 2xx raises
ApiErrorwith the RFC 9457Problem(type,title,status,detail,instance,code,errors[]); a body that is not a problem becomesabout:blank. No usable answer raisesTransportErrorwithtimedOut(). Both extendCryptoServiceException. - Retries are opt-in and safe.
RetryOptionsretries 429, 503, 504 and connection failures with full-jitter backoff andRetry-After; routes that create or delete server state are retried only after 429 or 503. - No secrets in logs. Credentials, keys, plaintexts and bodies never
appear in exception messages or
toString; the SDK logs nothing.
CryptoServiceClient client = CryptoServiceClient.builder()
.baseUrl(System.getenv().getOrDefault("CRYPTO_SERVICE_URL", "http://127.0.0.1:3101"))
.apiKey(System.getenv("CRYPTO_SERVICE_API_KEY"))
.build();
// Async: start several calls, then combine them.
CompletableFuture<HashResult> sha = client.hashAsync(new HashRequest(HashAlgorithm.SHA256, "abc"));
CompletableFuture<HashResult> b3 = client.hashAsync(new HashRequest(HashAlgorithm.BLAKE3, "abc"));
System.out.println(sha.thenCombine(b3, (x, y) -> x.digest() + " " + y.digest()).join());
// Errors: the RFC 9457 problem the server sent.
try {
client.sign(new SignRequest("k_AAAAAAAAAAAAAAAAAAAAAA", "m"));
} catch (ApiError e) {
System.out.println(e.status() + " " + e.problem().code());
}
client.close();
Configuration¶
| Builder method | Default | Effect |
|---|---|---|
baseUrl(String) |
required | The server, for example http://127.0.0.1:3101; http or https with a host, no user info, query or fragment |
apiKey(String) |
none | Sent as x-api-key |
token(String) |
none | A JWT, sent as Authorization: Bearer <token> |
timeout(Duration) |
30 seconds | Per attempt: connect and response headers |
deadline(Duration) |
none | The whole call, retries and waits included |
retry(RetryOptions) |
RetryOptions.NONE |
maxRetries (0), initialDelay (200 ms), maxDelay (2 s) |
traceparent(String) / autoTraceparent(boolean) |
none | A fixed W3C traceparent, or a fresh one per request |
responseListener(ResponseListener) |
none | Sees each response's status and headers (never a body) |
httpClient(HttpClient) |
the client's own | Inject a client for tests or a proxy; it must not follow redirects |
The blocking methods work from any thread pool, and from virtual threads on Java 21 without extra setup:
try (CryptoServiceClient client = CryptoServiceClient.builder()
.baseUrl(System.getenv().getOrDefault("CRYPTO_SERVICE_URL", "http://127.0.0.1:3101"))
.apiKey(System.getenv("CRYPTO_SERVICE_API_KEY"))
.retry(RetryOptions.of(2))
.deadline(Duration.ofSeconds(10))
.build()) {
ExecutorService pool = Executors.newFixedThreadPool(4); // or a virtual-thread executor on 21+
List<Future<String>> digests = new ArrayList<>();
for (String text : List.of("a", "b", "c")) {
digests.add(pool.submit(() -> client.hash(new HashRequest(HashAlgorithm.SHA256, text)).digest()));
}
for (Future<String> digest : digests) {
System.out.println(digest.get());
}
pool.shutdown();
}
Examples¶
Each file in examples/ is a runnable program. make
examples compiles them against the built SDK and runs every one against
the server at CRYPTO_SERVICE_URL; CI does the same in its conformance
job, so they cannot rot.
| Example | Shows |
|---|---|
Hash.java |
hash(...): SHA-256 of "abc", checked against the FIPS 180-2 vector |
AeadRoundTrip.java |
encrypt and decrypt (XChaCha20-Poly1305) with a synthetic hex key |
SignVerify.java |
A server-held Ed25519 key: generateKeyPair, sign by keyId, verify, deleteKey |
MlKem.java |
ML-KEM-768: mlKemEncapsulate to the public key, mlKemDecapsulate by keyId |
ErrorHandling.java |
ApiError with the problem's code and errors[], and TransportError |
ConcurrentHashes.java |
Twenty calls in flight at once through the async API |
When not to use Crypto Service¶
- You cannot reach a crypto-server. Every call goes to it; nothing works offline, and the SDK has no local fallback by design (ADR 0001).
- You need the deprecated v1 routes or
/metricsas typed methods. v1 is sunset on 2027-01-01 and/metricsis for scrapers; both are reachable only throughrequest. - You need very high request rates from one principal. crypto-server
meters each principal (60 requests a minute at the pinned commit);
batch with
streamSign/streamVerifyor spread load over principals. - You are on Java 11 or older. The floor is Java 17.
Development¶
make check
make regression
make conformance
make bench
make fuzz
make docs-lint
make check runs everything CI's build job runs, without a server:
javac -Xlint:all -Werror, the unit tests and fuzz seeds, JaCoCo at
100 % line and branch coverage, PMD with the suite's complexity
ceilings, and the compile of every example and README snippet.
make regression builds the pinned crypto-server, starts it on a
loopback port and adds the conformance kit, every example, every README
snippet and the benchmark smoke run; it is what the CI conformance job
runs. make conformance runs the kit against CRYPTO_SERVICE_URL and
fails if it is unset. Every gate is in DEVELOPMENT.md.
Security¶
Report a vulnerability privately through GitHub private vulnerability reporting, never in a public issue (SECURITY.md). The assurance case sets out the threat model, trust boundaries and how each weakness is countered.
The SDK implements no cryptography: keys are generated, held and used by the server, and the client sends what you give it to the base URL you configure. It never follows redirects, so credentials cannot reach another origin, and it has no option to disable TLS verification. It writes no files and logs nothing. Use https off loopback.
Responses are untrusted input. Three Jazzer fuzz targets
(src/fuzz/java/) feed arbitrary bytes to the problem parser, to every
success decoder and to the Retry-After parser; their seeds replay in
every build and CI fuzzes each target for 60 seconds on every pull
request. Text the server chose is escaped before it reaches an
exception message or toString, so it cannot forge log lines. Dependencies are
pinned by SHA-256 (.mvn/checksums/) and audited with OSV-Scanner over
the SBOM.
Documentation¶
User manual · API reference (Javadoc) · Developer docs · Ecosystem map
Also: Architecture · Decisions · Benchmarks · Packaging · Reproducing a release · Assurance case · Roadmap · Policies · Conformance kit · Changelog · Governance · Support
Stability guarantees¶
The project is pre-1.0 and versions advance in 0.0.1 steps, in
lockstep with the crypto-service suite. The breaking axis is the public
API of co.cryptoservice.sdk (method names and signatures, record
components, exception types and their hierarchy); the changelog calls
out any change to it, and a japicmp check in CI compares each build with
the last release on Maven Central and fails on a binary or source
incompatibility. The client sends
the request shapes the conformance kit pins; a change to what it sends
or to which exception a given answer raises is a breaking change even
when no signature moves. The deprecated v1 routes are excluded from the
typed surface. The Java floor moves only as described in the
toolchain policy, announced in the changelog.
License¶
This project is dual-licensed under either:
- Apache License, Version 2.0 (
LICENSE-APACHEor https://www.apache.org/licenses/LICENSE-2.0) - MIT License (
LICENSE-MITor https://opensource.org/licenses/MIT)
at your option. Dependencies keep their own licences.