= Crypto (JCE) Component
:doctitle: Crypto (JCE)
:shortname: crypto
:artifactid: camel-crypto
:description: Sign and verify exchanges using the Signature Service of the Java Cryptographic Extension (JCE).
:since: 2.3
:supportlevel: Stable
:tabs-sync-option:
:component-header: Only producer is supported
//Manually maintained attributes
:camel-spring-boot-name: crypto

*Since Camel {since}*

*{component-header}*

With Camel cryptographic endpoints and Java's Cryptographic extension, it
is possible to create Digital Signatures for Exchanges.
Camel provides a pair of flexible endpoints which get used in concert to
create a signature for an exchange in one part of the exchange's
workflow and then verify the signature in a later part of the workflow.

Maven users will need to add the following dependency to their `pom.xml`
for this component:

[source,xml]
------------------------------------------------------------
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-crypto</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
------------------------------------------------------------

== Introduction

Digital signatures make use of Asymmetric Cryptographic techniques to
sign messages. From a (very) high level, the algorithms use pairs of
complimentary keys with the special property that data encrypted with
one key can only be decrypted with the other. One, the private key, is
closely guarded and used to 'sign' the message while the other, public
key, is shared around to anyone interested in verifying the signed
messages. Messages are signed by using the private key to encrypting a
digest of the message. This encrypted digest is transmitted along with
the message. On the other side, the verifier recalculates the message
digest and uses the public key to decrypt the digest in the
signature. If both digests match, the verifier knows only the holder of
the private key could have created the signature.

Camel uses the Signature service from the Java Cryptographic Extension
to do all the heavy cryptographic lifting required to create exchange
signatures. The following are some excellent resources for explaining
the mechanics of Cryptography, Message digests and Digital Signatures
and how to leverage them with the JCE.

* Bruce Schneier's Applied Cryptography
* Beginning Cryptography with Java by David Hook
* The ever insightful Wikipedia
http://en.wikipedia.org/wiki/Digital_signature[Digital_signatures]

== URI format

As mentioned, Camel provides a pair of crypto endpoints to create and
verify signatures

----------------------------
crypto:sign:name[?options]
crypto:verify:name[?options]
----------------------------

* `crypto:sign` creates the signature and stores it in the Header keyed
by the constant
`org.apache.camel.component.crypto.DigitalSignatureConstants.SIGNATURE`,
i.e., `"CamelDigitalSignature"`.
* `crypto:verify` will read in the contents of this header and do the
verification calculation.

To correctly function, the sign and verify process needs a pair
of keys to be shared, signing requiring a `PrivateKey` and verifying a
`PublicKey` (or a `Certificate` containing one). Using the JCE it is
very simple to generate these key pairs, but it is usually most secure to
use a KeyStore to house and share your keys. The DSL is very flexible
about how keys are supplied and provides a number of mechanisms.

Note a `crypto:sign` endpoint is typically defined in one route and the
complimentary `crypto:verify` in another, though for simplicity in the
examples they appear one after the other. It goes without saying that
both signing and verifying should be configured identically.


// component options: START
include::partial$component-configure-options.adoc[]
include::partial$component-endpoint-options.adoc[]
include::partial$component-endpoint-headers.adoc[]
// component options: END

== Usage

=== Raw keys

The most basic way to sign and verify an exchange is with a
KeyPair as follows.

[source,java]
----
KeyPair keyPair = KeyGenerator.getInstance("RSA").generateKeyPair();

from("direct:sign")
    .setHeader(DigitalSignatureConstants.SIGNATURE_PRIVATE_KEY, constant(keys.getPrivate()))
    .to("crypto:sign:message")
    .to("direct:verify");

from("direct:verify")
    .setHeader(DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT, constant(keys.getPublic()))
    .to("crypto:verify:check");
----

The same can be achieved with the xref:manual::spring-xml-extensions.adoc[Spring
XML Extensions] using references to keys

=== KeyStores and Aliases.

The JCE provides a very versatile keystore concept for housing pairs of
private keys and certificates, keeping them encrypted and password
protected. They can be retrieved by applying an alias to the retrieval
APIs. There are a number of ways to get keys and Certificates into a
keystore, most often this is done with the external 'keytool'
application.

The following command will create a keystore containing a key and certificate aliased by `bob`, which can be used in the following examples. The password for the keystore and the key is `letmein`.

[source,sh]
----
keytool -genkey -keyalg RSA -keysize 2048 -keystore keystore.jks -storepass letmein -alias bob -dname "CN=Bob,OU=IT,O=Camel" -noprompt
----

The following route first signs an exchange using Bob's alias from the KeyStore bound into the Camel Registry, and then verifies it using the same alias.

[source,java]
----
from("direct:sign")
    .to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein")
    .log("Signature: ${header.CamelDigitalSignature}")
    .to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein")
    .log("Verified: ${body}");
----

The following code shows how to load the keystore created using the above `keytool` command and bind it into the registry with the name `myKeystore` for use in the above route. The example makes use of the `@Configuration` and `@BindToRegistry` annotations introduced in Camel 3 to instantiate the KeyStore and register it with the name `myKeyStore`.

[source,java]
----
@Configuration
public class KeystoreConfig {
    
    @BindToRegistry
    public KeyStore myKeystore() throws Exception {
        KeyStore store = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream("keystore.jks")) {
            store.load(fis, "letmein".toCharArray());
        }
        return store;
    }
}
----

Again in Spring, a ref is used to look up an actual keystore instance.

=== Changing JCE Provider and Algorithm

Changing the Signature algorithm or the Security provider is a simple
matter of specifying their names. You will need to also use Keys that
are compatible with the algorithm you choose.

=== Changing the Signature Message Header

It may be desirable to change the message header used to store the
signature. A different header name can be specified in the route
definition as follows

[source,java]
----
from("direct:sign")
    .to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature")
    .log("Signature: ${header.mySignature}")
    .to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature");
----

=== Changing the bufferSize

In case you need to update the size of the buffer...

=== Supplying Keys dynamically.

When using a Recipient list or similar EIP, the recipient of an exchange
can vary dynamically. Using the same key across all recipients may be
neither feasible nor desirable. It would be useful to be able to specify
signature keys dynamically on a per-exchange basis. The exchange could
then be dynamically enriched with the key of its target recipient prior
to signing. To facilitate this, the signature mechanisms allow for keys
to be supplied dynamically via the message headers below

* `DigitalSignatureConstants.SIGNATURE_PRIVATE_KEY`, `"CamelSignaturePrivateKey"`
* `DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT`, `"CamelSignaturePublicKeyOrCert"`

Even better would be to dynamically supply a keystore alias. Again, the
alias can be supplied in a message header

* `DigitalSignatureConstants.KEYSTORE_ALIAS`, `"CamelSignatureKeyStoreAlias"`

The header would be set as follows:

[source,java]
-------------------------------------------------------------------------------------------------
Exchange unsigned = getMandatoryEndpoint("direct:alias-sign").createExchange();
unsigned.getIn().setBody(payload);
unsigned.getIn().setHeader(DigitalSignatureConstants.KEYSTORE_ALIAS, "bob");
unsigned.getIn().setHeader(DigitalSignatureConstants.KEYSTORE_PASSWORD, "letmein".toCharArray());
template.send("direct:alias-sign", unsigned);
Exchange signed = getMandatoryEndpoint("direct:alias-sign").createExchange();
signed.getIn().copyFrom(unsigned.getMessage());
signed.getIn().setHeader(DigitalSignatureConstants.KEYSTORE_ALIAS, "bob");
template.send("direct:alias-verify", signed);
-------------------------------------------------------------------------------------------------

== Using Post-Quantum Cryptography (PQC) Algorithms

The Digital Signature EIP supports Post-Quantum Cryptography algorithms through the standard JCE provider mechanism.
Since the `algorithm` and `provider` options accept any value supported by the underlying JCE implementation, you can use PQC signature algorithms such as ML-DSA (NIST FIPS 204) by registering a Bouncy Castle provider and supplying the corresponding keys.

This approach is useful when you want to apply PQC signatures directly using the `crypto:sign` / `crypto:verify` pair without the full `camel-pqc` component.
For hybrid signatures (combining classical + PQC) or key lifecycle management, use the xref:components::pqc-component.adoc[PQC component] instead.

=== Prerequisites

Add the Bouncy Castle provider dependencies to your project:

[source,xml]
----
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk18on</artifactId>
    <version>${bouncycastle.version}</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk18on</artifactId>
    <version>${bouncycastle.version}</version>
</dependency>
----

Register the Bouncy Castle provider at application startup:

[source,java]
----
import org.bouncycastle.jce.provider.BouncyCastleProvider;

Security.addProvider(new BouncyCastleProvider());
----

=== ML-DSA (NIST FIPS 204)

ML-DSA (Module-Lattice Digital Signature Algorithm, formerly Dilithium) is the primary NIST-standardized post-quantum signature algorithm.

==== Java DSL

[tabs]
====
Raw keys::
+
[source,java]
----
private KeyPair mlDsaKeyPair;

private KeyPair getMlDsaKeyPair() throws Exception {
    if (mlDsaKeyPair == null) {
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA", "BC");
        kpGen.initialize(MLDSAParameterSpec.ml_dsa_65);
        mlDsaKeyPair = kpGen.generateKeyPair();
    }
    return mlDsaKeyPair;
}

@BindToRegistry("mlDsaPrivateKey")
public PrivateKey mlDsaPrivateKey() throws Exception {
    return getMlDsaKeyPair().getPrivate();
}

@BindToRegistry("mlDsaPublicKey")
public PublicKey mlDsaPublicKey() throws Exception {
    return getMlDsaKeyPair().getPublic();
}

from("direct:sign")
    .to("crypto:sign:pqc?algorithm=ML-DSA&provider=BC&privateKeyName=#mlDsaPrivateKey")
    .to("direct:verify");

from("direct:verify")
    .to("crypto:verify:pqc?algorithm=ML-DSA&provider=BC&publicKeyName=#mlDsaPublicKey")
    .to("mock:result");
----

Dynamic keys via headers::
+
[source,java]
----
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA", "BC");
kpGen.initialize(MLDSAParameterSpec.ml_dsa_65);
KeyPair kp = kpGen.generateKeyPair();

from("direct:sign")
    .setHeader(DigitalSignatureConstants.SIGNATURE_PRIVATE_KEY, constant(kp.getPrivate()))
    .to("crypto:sign:pqc?algorithm=ML-DSA&provider=BC")
    .to("direct:verify");

from("direct:verify")
    .setHeader(DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT, constant(kp.getPublic()))
    .to("crypto:verify:pqc?algorithm=ML-DSA&provider=BC")
    .to("mock:result");
----
====

==== YAML DSL

[source,yaml]
----
- route:
    id: sign-route
    from:
      uri: direct:sign
    steps:
      - to:
          uri: crypto:sign:pqc
          parameters:
            algorithm: ML-DSA
            provider: BC
            privateKeyName: "#mlDsaPrivateKey"
      - to:
          uri: direct:verify

- route:
    id: verify-route
    from:
      uri: direct:verify
    steps:
      - to:
          uri: crypto:verify:pqc
          parameters:
            algorithm: ML-DSA
            provider: BC
            publicKeyName: "#mlDsaPublicKey"
      - to:
          uri: mock:result
----

==== ML-DSA parameter sets

The following ML-DSA parameter sets are available:

[cols="1,1,1,1"]
|===
| Parameter Set | Security Level | Signature Size | Use Case

| `ml_dsa_44`
| NIST Level 2
| ~2,420 bytes
| General-purpose signing

| `ml_dsa_65`
| NIST Level 3
| ~3,309 bytes
| Recommended default

| `ml_dsa_87`
| NIST Level 5
| ~4,627 bytes
| Highest security
|===

=== SLH-DSA (NIST FIPS 205)

SLH-DSA (Stateless Hash-Based Digital Signature Algorithm, formerly SPHINCS+) is the secondary NIST-standardized PQC signature algorithm, based on hash functions.

[source,java]
----
private KeyPair slhDsaKeyPair;

private KeyPair getSlhDsaKeyPair() throws Exception {
    if (slhDsaKeyPair == null) {
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance("SLH-DSA", "BC");
        kpGen.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128s);
        slhDsaKeyPair = kpGen.generateKeyPair();
    }
    return slhDsaKeyPair;
}

@BindToRegistry("slhDsaPrivateKey")
public PrivateKey slhDsaPrivateKey() throws Exception {
    return getSlhDsaKeyPair().getPrivate();
}

@BindToRegistry("slhDsaPublicKey")
public PublicKey slhDsaPublicKey() throws Exception {
    return getSlhDsaKeyPair().getPublic();
}

from("direct:sign")
    .to("crypto:sign:pqc?algorithm=SLH-DSA&provider=BC&privateKeyName=#slhDsaPrivateKey")
    .to("direct:verify");

from("direct:verify")
    .to("crypto:verify:pqc?algorithm=SLH-DSA&provider=BC&publicKeyName=#slhDsaPublicKey")
    .to("mock:result");
----

=== Hybrid Signatures (Classical + PQC)

For hybrid signatures that combine a classical algorithm (e.g., ECDSA) with a PQC algorithm (e.g., ML-DSA) in a single route, the recommended approach is to use the xref:components::pqc-component.adoc[PQC component] which provides built-in hybrid operations.

==== Using the PQC component (recommended)

The `camel-pqc` component has dedicated `hybridSign` and `hybridVerify` operations that produce a single combined signature:

[tabs]
====
Java DSL::
+
[source,java]
----
from("direct:sign")
    .to("pqc:hybrid?operation=hybridSign"
        + "&signatureAlgorithm=MLDSA"
        + "&classicalSignatureAlgorithm=ECDSA_P256")
    .to("direct:verify");

from("direct:verify")
    .to("pqc:hybrid?operation=hybridVerify"
        + "&signatureAlgorithm=MLDSA"
        + "&classicalSignatureAlgorithm=ECDSA_P256")
    .to("mock:result");
----

YAML DSL::
+
[source,yaml]
----
- route:
    id: hybrid-sign-route
    from:
      uri: direct:sign
    steps:
      - to:
          uri: pqc:hybrid
          parameters:
            operation: hybridSign
            signatureAlgorithm: MLDSA
            classicalSignatureAlgorithm: ECDSA_P256
      - to:
          uri: direct:verify

- route:
    id: hybrid-verify-route
    from:
      uri: direct:verify
    steps:
      - to:
          uri: pqc:hybrid
          parameters:
            operation: hybridVerify
            signatureAlgorithm: MLDSA
            classicalSignatureAlgorithm: ECDSA_P256
      - to:
          uri: mock:result
----
====

Other hybrid combinations include:

* `ED25519` + `MLDSA` — Edwards curve + ML-DSA
* `RSA_3072` + `MLDSA` — RSA 3072-bit + ML-DSA
* `ECDSA_P384` + `SLHDSA` — ECDSA P-384 + SLH-DSA

See the xref:components::pqc-component.adoc[PQC component] for the full list of supported classical algorithms and details on the hybrid wire format.

==== Chaining crypto: endpoints (manual approach)

Alternatively, you can chain two `crypto:sign` / `crypto:verify` endpoints to produce both a classical and a PQC signature, storing each in a separate header:

[source,java]
----
from("direct:sign")
    // Classical ECDSA signature
    .to("crypto:sign:classical?algorithm=SHA256withECDSA&privateKeyName=#ecPrivateKey"
        + "&signatureHeaderName=ClassicalSignature")
    // PQC ML-DSA signature
    .to("crypto:sign:pqc?algorithm=ML-DSA&provider=BC&privateKeyName=#mlDsaPrivateKey"
        + "&signatureHeaderName=PQCSignature")
    .to("direct:verify");

from("direct:verify")
    // Verify classical signature
    .to("crypto:verify:classical?algorithm=SHA256withECDSA&publicKeyName=#ecPublicKey"
        + "&signatureHeaderName=ClassicalSignature")
    // Verify PQC signature
    .to("crypto:verify:pqc?algorithm=ML-DSA&provider=BC&publicKeyName=#mlDsaPublicKey"
        + "&signatureHeaderName=PQCSignature")
    .to("mock:result");
----

NOTE: The chaining approach stores two independent signatures in separate headers, while the PQC component's hybrid operations produce a single combined signature.
For new implementations, the PQC component's hybrid operations are recommended as they handle the wire format, key management, and verification logic in a single step.

=== Choosing Between camel-crypto and camel-pqc

[cols="1,1,1"]
|===
| Feature | `camel-crypto` (Digital Signature EIP) | `camel-pqc` component

| PQC-only signatures
| Supported (set `algorithm` and `provider`)
| Supported (built-in algorithm support)

| Hybrid signatures
| Manual chaining of two endpoints
| Built-in `hybridSign` / `hybridVerify`

| Key lifecycle management
| Not included
| Generate, rotate, expire, revoke keys

| Key encapsulation (KEM)
| Not supported
| Built-in support

| Additional dependencies
| Only Bouncy Castle
| Only Bouncy Castle

| Best for
| Adding PQC to existing crypto: routes
| New PQC-focused implementations
|===

include::spring-boot:partial$starter.adoc[]
