Encryption plugin library for Azure Cosmos DB Java SDK for Java

The Azure Cosmos Encryption Plugin is used for encrypting data with a user-provided key before saving into Cosmos DB and decrypting it when reading back from the database.

Source code | Package (Maven) | API reference documentation | Product documentation | Samples

Getting started

Include the package


Refer to maven central for previous releases

Refer to javadocs for more details on the package


SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the SLF4J user manual for more information.

The SDK provides Reactor Core-based async APIs. You can read more about Reactor Core and Flux/Mono types here

Key concepts

The Azure Cosmos Encryption Plugin is used for encrypting data with a user-provided key before saving into Cosmos DB and decrypting it when reading back from the database. Underneath it uses Azure Cosmos DB Java SDK which provides client-side logical representation to access the Azure Cosmos DB SQL API. A Cosmos DB account contains zero or more databases, a database (DB) contains zero or more containers, and a container contains zero or more items. You may read more about databases, containers, and items here. A few important properties are defined at the level of the container, among them are provisioned throughput and partition key.


The following section provides several code snippets covering some of the most common Cosmos Encryption API tasks, including:

Create Cosmos Encryption Client

// Create a new CosmosEncryptionAsyncClient
CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder()
    .endpoint("<YOUR ENDPOINT HERE>")
    .key("<YOUR KEY HERE>")
KeyEncryptionKeyClientBuilder keyEncryptionKeyClientBuilder = new KeyEncryptionKeyClientBuilder().credential(tokenCredentials);
CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient =
    new CosmosEncryptionClientBuilder().cosmosAsyncClient(cosmosAsyncClient).keyEncryptionKeyResolver(

Create Cosmos Encryption Database

You need to first create a Database and using the cosmos encryption client created in the previous example, you can create a cosmos encryption database proxy object like this:

// This will create a database with the regular cosmosAsyncClient.
CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosAsyncClient()
    .createDatabaseIfNotExists("<YOUR DATABASE NAME>")
    // TIP: Our APIs are Reactor Core based, so try to chain your calls
    .map(databaseResponse ->
        // Get a reference to the encryption database
        // This will create a cosmos encryption database proxy object.
    .block(); // Blocking for demo purposes (avoid doing this in production unless you must)

Create Cosmos Encryption Container

You need to first create a Container with ClientEncryptionPolicy and using the cosmos encryption database object created in the previous example, you can create a cosmos encryption container proxy object like this:

//Create Client Encryption Key
EncryptionKeyWrapMetadata metadata = new EncryptionKeyWrapMetadata(this.cosmosEncryptionAsyncClient.getKeyEncryptionKeyResolverName(), "key", "tempmetadata", EncryptionAlgorithm.RSA_OAEP.toString());
CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase
    .createClientEncryptionKey("key", CosmosEncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256.getName(), metadata)
    // TIP: Our APIs are Reactor Core based, so try to chain your calls
    .then(Mono.defer(() -> {
        //Create Encryption Container
        ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath();

        List<ClientEncryptionIncludedPath> paths = new ArrayList<>();
        ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(paths);
        CosmosContainerProperties properties = new CosmosContainerProperties("<YOUR CONTAINER NAME>", "/mypk");
        return cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties);
    .map(containerResponse ->
        // Create a reference to the encryption container
        // This will create a cosmos encryption container proxy object.
    .block(); // Blocking for demo purposes (avoid doing this in production unless you must)

CRUD operation on Items

// Create an item
Pojo pojo = new Pojo();
pojo.setSensitiveString("Sensitive Information need to be encrypted");
    .flatMap(response -> {
        System.out.println("Created item: " + response.getItem());
        // Read that item 👓
        return cosmosEncryptionAsyncContainer.readItem(response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
    .flatMap(response -> {
        System.out.println("Read item: " + response.getItem());
        // Replace that item 🔁
        Pojo p = response.getItem();
        pojo.setSensitiveString("New Sensitive Information");
        return cosmosEncryptionAsyncContainer.replaceItem(p, response.getItem().getId(),
            new PartitionKey(response.getItem().getId()));
    // delete that item 💣
    .flatMap(response -> cosmosEncryptionAsyncContainer.deleteItem(response.getItem().getId(),
        new PartitionKey(response.getItem().getId())))

We have a get started sample app available here.



Azure Cosmos DB is a fast and flexible distributed database that scales seamlessly with guaranteed latency and throughput. You do not have to make major architecture changes or write complex code to scale your database with Azure Cosmos DB. Scaling up and down is as easy as making a single API call or SDK method call. However, because Azure Cosmos DB is accessed via network calls there are client-side optimizations you can make to achieve peak performance when using Azure Cosmos DB Java SDK v4.

  • Performance guide covers these client-side optimizations.

  • Troubleshooting Guide covers common issues, workarounds, diagnostic steps, and tools when you use Azure Cosmos DB Java SDK v4 with Azure Cosmos DB SQL API accounts.

Enable Client Logging

Azure Cosmos DB Java SDK v4 uses SLF4j as the logging facade that supports logging into popular logging frameworks such as log4j and logback.

For example, if you want to use log4j as the logging framework, add the following libs in your Java classpath.


Also, add a log4j config.

# this is a sample log4j configuration

# Set root logger level to INFO and its only appender to A1.
log4j.rootLogger=INFO, A1

# A1 is set to be a ConsoleAppender.

# A1 uses PatternLayout.
log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n

Next steps


This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.