Skip navigation links

Azure SDK for Java Reference Documentation

Current version is 4.2.0-beta.6, click here for the index

Azure Key Vault Certificate client library for Java

See: Description

Packages 
Package Description
com.azure.security.keyvault.certificates
Package containing classes for creating CertificateAsyncClient and CertificateClient to perform operations on Azure Key Vault.
com.azure.security.keyvault.certificates.models
This package contains model classes for Azure Key Vault Certificates
Current version is 4.2.0-beta.6, click here for the index

Azure Key Vault Certificate client library for Java

Azure Key Vault allows you to securely manage and tightly control your certificates. The Azure Key Vault Certificate client library supports certificates backed by RSA and EC keys.

Multiple certificates and multiple versions of the same certificate can be kept in the Key Vault. Cryptographic keys in Key Vault backing the certificates are represented as JSON Web Key [JWK] objects. This library offers operations to create, retrieve, update, delete, purge, backup, restore, and list the certificates, as well as its versions.

Source code | API reference documentation | Product documentation | Samples

Getting started

Adding the package to your project

Maven dependency for the Azure Key Vault Certificate client library. Add it to your project's POM file.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-security-keyvault-certificates</artifactId>
    <version>4.2.0-beta.6</version>
</dependency>

Prerequisites

Authenticate the client

In order to interact with the Azure Key Vault service, you'll need to create an instance of the CertificateClient class. You need a vault url and client secret credentials (client id, client secret, tenant id) to instantiate a client object using the DefaultAzureCredential examples shown in this document.

The DefaultAzureCredential way of authentication by providing client secret credentials is being used in this getting started section but you can find more ways to authenticate with azure-identity.

Create/Get credentials

To create/get client secret credentials you can use the Azure Portal, Azure CLI or Azure Cloud Shell

Here is an Azure Cloud Shell snippet below to

Create certificate client

Once you've populated the AZURECLIENTID, AZURECLIENTSECRET, and AZURETENANTID environment variables and replaced your-key-vault-url with the URI returned above, you can create the CertificateClient:

import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.certificates.CertificateClient;
import com.azure.security.keyvault.certificates.CertificateClientBuilder;

CertificateClient certificateClient = new CertificateClientBuilder()
    .vaultUrl("<your-key-vault-url>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

NOTE: For using an asynchronous client use CertificateAsyncClient instead of CertificateClient and call buildAsyncClient()

Key concepts

Certificate

Azure Key Vault supports certificates with secret content types (PKCS12 & PEM). The certificate can be backed by keys in Azure Key Vault of types (EC & RSA). In addition to the certificate policy, the following attributes may be specified: * enabled: Specifies whether the certificate is enabled and usable. * created: Indicates when this version of the certificate was created. * updated: Indicates when this version of the certificate was updated.

Certificate client

The certificate client performs the interactions with the Azure Key Vault service for getting, setting, updating, deleting, and listing certificates and its versions. The client also supports CRUD operations for certificate issuers and contacts in the key vault. Asynchronous (CertificateAsyncClient) and synchronous (CertificateClient) clients exist in the SDK allowing for the selection of a client based on an application's use case. Once you've initialized a certificate, you can interact with the primary resource types in Azure Key Vault.

Examples

Sync API

The following sections provide several code snippets covering some of the most common Azure Key Vault Certificate service tasks, including: - Create a certificate - Retrieve a certificate - Update an existing certificate - Delete a certificate - List certificates

Create a certificate

Create a certificate to be stored in the Azure Key Vault. - beginCreateCertificate creates a new certificate in the Azure Key Vault. If a certificate with the same name already exists then a new version of the certificate is created.

import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.SyncPoller;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.certificates.CertificateClient;
import com.azure.security.keyvault.certificates.CertificateClientBuilder;
import com.azure.security.keyvault.certificates.models.CertificateOperation;
import com.azure.security.keyvault.certificates.models.CertificatePolicy;
import com.azure.security.keyvault.certificates.models.KeyVaultCertificate;
import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; 

CertificateClient certificateClient = new CertificateClientBuilder()
    .vaultUrl("<your-key-vault-url>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certificatePoller =
    certificateClient.beginCreateCertificate("certificateName", CertificatePolicy.getDefault());
certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED);
KeyVaultCertificate certificate = certificatePoller.getFinalResult();
System.out.printf("Certificate created with name \"%s\"%n", certificate.getName());

Retrieve a certificate

Retrieve a previously stored certificate by calling getCertificate or getCertificateVersion.

KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate("<certificate-name>");
System.out.printf("Recevied certificate with name \"%s\", version %s and secret id %s%n",
    certificate.getProperties().getName(), certificate.getProperties().getVersion(), certificate.getSecretId());

Update an existing certificate

Update an existing certificate by calling updateCertificateProperties.

// Get the certificate to update.
KeyVaultCertificate certificate = certificateClient.getCertificate("<certificate-name>");
// Update certificate enabled status.
certificate.getProperties().setEnabled(false);
KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties());
System.out.printf("Updated certificate with name \"%s\" and enabled status \"%s\"%n",
    updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled());

Delete a certificate

Delete an existing certificate by calling beginDeleteCertificate.

SyncPoller<DeletedCertificate, Void> deleteCertificatePoller =
    certificateClient.beginDeleteCertificate("<certificate-name>");

// Deleted certificate is accessible as soon as polling beings.
PollResponse<DeletedCertificate> pollResponse = deleteCertificatePoller.poll();

// Deletion date only works for a SoftDelete-enabled Key Vault.
System.out.printf("Deleted certificate with name \"%s\" and recovery id %s", pollResponse.getValue().getName(),
    pollResponse.getValue().getRecoveryId());

// Certificate is being deleted on server.
deleteCertificatePoller.waitForCompletion();

List certificates

List the certificates in the key vault by calling listPropertiesOfCertificates.

// List operations don't return the certificates with their full information. So, for each returned certificate we call
// getCertificate to get the certificate with all its properties excluding the policy.
for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) {
    KeyVaultCertificate certificateWithAllProperties =
        certificateClient.getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion());
    System.out.printf("Received certificate with name \"%s\" and secret id %s",
        certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId());
}

Async API

The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Certificate service tasks, including: - Create a certificate asynchronously - Retrieve a certificate asynchronously - Update an existing certificate asynchronously - Delete a certificate asynchronously - List certificates asynchronously

Note : You should add System.in.read() or Thread.sleep() after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits.

Create a certificate asynchronously

Create a certificate to be stored in the Azure Key Vault. - beginCreateCertificate creates a new certificate in the Azure Key Vault. If a certificate with same name already exists then a new version of the certificate is created.

import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.certificates.CertificateClient;
import com.azure.security.keyvault.certificates.CertificateClientBuilder;

CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
    .vaultUrl("<your-key-vault-url>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildAsyncClient();

// Creates a certificate using the default policy and polls on its progress.
certificateAsyncClient.beginCreateCertificate("<certificate-name>", CertificatePolicy.getDefault())
    .subscribe(pollResponse -> {
        System.out.println("---------------------------------------------------------------------------------");
        System.out.println(pollResponse.getStatus());
        System.out.println(pollResponse.getValue().getStatus());
        System.out.println(pollResponse.getValue().getStatusDetails());
    });

Retrieve a certificate asynchronously

Retrieve a previously stored certificate by calling getCertificate or getCertificateVersion.

certificateAsyncClient.getCertificate("<certificate-name>")
    .subscribe(certificateResponse ->
        System.out.printf("Certificate was returned with name \"%s\" and secretId %s%n",
            certificateResponse.getProperties().getName(), certificateResponse.getSecretId()));

Update an existing certificate asynchronously

Update an existing certificate by calling updateCertificateProperties.

certificateAsyncClient.getCertificate("<certificate-name>")
    .subscribe(certificateResponseValue -> {
        KeyVaultCertificate certificate = certificateResponseValue;
        // Update enabled status of the certificate.
        certificate.getProperties().setEnabled(false);
        certificateAsyncClient.updateCertificateProperties(certificate.getProperties())
            .subscribe(certificateResponse ->
                System.out.printf("Certificate's enabled status: %s%n",
                    certificateResponse.getProperties().isEnabled()));
    });

Delete a certificate asynchronously

Delete an existing certificate by calling beginDeleteCertificate.

certificateAsyncClient.beginDeleteCertificate("<certificate-name>")
    .subscribe(pollResponse -> {
        System.out.printf("Deletion status: %s%n", pollResponse.getStatus());
        System.out.printf("Deleted certificate name: %s%n", pollResponse.getValue().getName());
        System.out.printf("Certificate deletion date: %s%n", pollResponse.getValue().getDeletedOn());
    });

List certificates asynchronously

List the certificates in the Azure Key Vault by calling listPropertiesOfCertificates.

// The List Certificates operation returns certificates without their full properties, so for each certificate returned
// we call `getCertificate` to get all its attributes excluding the policy.
certificateAsyncClient.listPropertiesOfCertificates()
    .subscribe(certificateProperties ->
        certificateAsyncClient.getCertificateVersion(certificateProperties.getName(),
            certificateProperties.getVersion())
            .subscribe(certificateResponse ->
                System.out.printf("Received certificate with name \"%s\" and key id %s", certificateResponse.getName(),
                    certificateResponse.getKeyId())));

Troubleshooting

General

Azure Key Vault Certificate clients raise exceptions. For example, if you try to retrieve a certificate after it is deleted a 404 error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.

try {
    certificateClient.getCertificate("<deleted-certificate-name>")
} catch (ResourceNotFoundException e) {
    System.out.println(e.getMessage());
}

Default HTTP client

All client libraries by default use the Netty HTTP client. Adding the above dependency will automatically configure the client library to use the Netty HTTP client. Configuring or changing the HTTP client is detailed in the HTTP clients wiki.

Default SSL library

All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an Uber JAR containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the performance tuning section of the wiki.

Next steps

Several Key Vault Java SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Key Vault.

Next steps samples

Samples are explained in detail here.

Additional documentation

For more extensive documentation on Azure Key Vault, see the API reference documentation.

Contributing

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. For details, visit https://cla.microsoft.com.

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 with any additional questions or comments.

Impressions

Skip navigation links
Visit the Azure for Java Developerssite for more Java documentation, including quick starts, tutorials, and code samples.

Copyright © 2021 Microsoft Corporation. All rights reserved.