Azure Key Vault allows you to create and store certificates in the Key Vault. Azure Key Vault client supports certificates backed by Rsa keys and Ec keys. It allows you to securely manage, tightly control your certificates.
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 and its versions.
Source code | API reference documentation | Product documentation | Samples
Maven dependency for Azure Key Client library. Add it to your project's pom file.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-keyvault-certificates</artifactId>
<version>4.0.0-preview.3</version>
</dependency>
-
Java Development Kit (JDK) with version 8 or above
-
An existing Azure Key Vault. If you need to create a Key Vault, you can use the Azure Cloud Shell to create one with this Azure CLI command. Replace
<your-resource-group-name>
and<your-key-vault-name>
with your own, unique names:az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name>
In order to interact with the Key Vault service, you'll need to create an instance of the CertificateClient class. You would need a vault url and client secret credentials (client id, client key, tenant id) to instantiate a client object using the default AzureCredential
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.
To create/get client key credentials you can use the Azure Portal, Azure CLI or Azure Cloud Shell
Here is Azure Cloud Shell snippet below to
-
Create a service principal and configure its access to Azure resources:
az ad sp create-for-rbac -n <your-application-name> --skip-assignment
Output:
{ "appId": "generated-app-ID", "displayName": "dummy-app-name", "name": "http://dummy-app-name", "password": "random-password", "tenant": "tenant-ID" }
-
Use the above returned credentials information to set AZURE_CLIENT_ID(appId), AZURE_CLIENT_SECRET(password) and AZURE_TENANT_ID(tenant) environment variables. The following example shows a way to do this in Bash:
export AZURE_CLIENT_ID="generated-app-ID" export AZURE_CLIENT_SECRET="random-password" export AZURE_TENANT_ID="tenant-ID"
-
Grant the above mentioned application authorization to perform key operations on the keyvault:
az keyvault set-policy --name <your-key-vault-name> --spn $AZURE_CLIENT_ID --certificate-permissions backup delete get list set
--certificate-permissions: Accepted values: backup, create, delete, deleteissuers, get, getissuers, import, list, listissuers, managecontacts, manageissuers, purge, recover, restore, setissuers, update
-
Use the above mentioned Key Vault name to retreive details of your Vault which also contains your Key Vault URL:
az keyvault show --name <your-key-vault-name>
Once you've populated the AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID environment variables and replaced your-vault-url with the above returned URI, you can create the CertificateClient:
import com.azure.identity.credential.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.certificates.CertificateClient;
CertificateClient client = new CertificateClientBuilder()
.endpoint(<your-vault-url>)
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
NOTE: For using Asynchronous client use CertificateAsyncClient instead of CertificateClient and call buildAsyncClient()
Azure Key Vault supports certificates with secret content types(PKCS12
& PEM
). The certificate can be backed by keys in 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 useable.
- created: Indicates when this version of the certificate was created.
- updated: Indicates when this version of the certificate was updated.
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. An asynchronous and synchronous, CertificateClient, client exists in the SDK allowing for 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 Key Vault.
The following sections provide several code snippets covering some of the most common Azure Key Vault Key Service tasks, including:
- Create a Certificate
- Retrieve a Certificate
- Update an existing Certificate
- Delete a Certificate
- List Certificates
Create a Certificate to be stored in the Azure Key Vault.
createCertificate
creates a new certificate in the key vault. if the certificate with name already exists then a new version of the certificate is created.
import com.azure.identity.credential.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.certificates.models.Certificate;
import com.azure.security.keyvault.certificates.models.CertificatePolicy;
import com.azure.security.keyvault.certificates.models.CertificateOperation;
import com.azure.security.keyvault.certificates.CertificateClient;
CertificateClient certificateClient = new CertificateClientBuilder()
.endpoint(<your-vault-url>)
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> metadataTags = new HashMap<>();
metadataTags.put("foo", "bar");
//By default blocks until certificate is created, unless a timeout is specified as an optional parameter.
try {
CertificateOperation certificateOperation = certificateClient.createCertificate("certificateName",
policy, Duration.ofSeconds(60));
System.out.printf("Certificate operation status %s \n", certificateOperation.status());
} catch (IllegalStateException e) {
// Certificate wasn't created in the specified duration.
// Log / Handle here
}
Retrieve a previously stored Certificate by calling getCertificate
or getCertificateWithPolicy
.
Certificate certificate = certificateClient.getCertificateWithPolicy("certificateName");
System.out.printf("Recevied certificate with name %s and version %s and secret id", certificate.name(),
certificate.version(), certificate.secretId());
Update an existing Certificate by calling updateCertificate
.
// Get the certificate to update.
Certificate certificate = certificateClient.getCertificateWithPolicy("certificateName");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
// Update certificate enabled status
certificate.enabled(false);
Certificate updatedCertificate = certificateClient.updateCertificate(certificate);
System.out.printf("Updated Certificate with name %s and enabled status %s", updatedCertificate.name(),
updatedCertificate.enabled());
Delete an existing Certificate by calling deleteCertificate
.
DeletedCertificate deletedCertificate = certificateClient.deleteCertificate("certificateName");
System.out.printf("Deleted certitifcate with name %s and recovery id %s", deletedCertificate.name(),
deletedCertificate.recoveryId());
List the certificates in the key vault by calling listCertificates
.
// 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 (CertificateBase certificate : certificateClient.listCertificates()) {
Certificate certificateWithAllProperties = certificateClient.getCertificate(certificate);
System.out.printf("Received certificate with name %s and secret id %s", certificateWithAllProperties.name(),
certificateWithAllProperties.secretId());
}
The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Key Service tasks, including:
- Create a Certificate Asynchronously
- Retrieve a Certificate Asynchronously
- Update an existing Certificate Asynchronously
- Delete a Certficate Asynchronously
- List Certificates Asynchronously
Create a Certificate to be stored in the Azure Key Vault.
createCertificate
creates a new key in the key vault. if the certificate with name already exists then a new version of the certificate is created.
import com.azure.identity.credential.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.certificates.models.Certificate;
import com.azure.security.keyvault.certificates.models.CertificatePolicy;
import com.azure.security.keyvault.certificates.models.CertificateOperation;
import com.azure.security.keyvault.certificates.CertificateAsyncClient;
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
//Creates a certificate and polls on its progress.
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver()
.subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Retrieve a previously stored Certificate by calling getCertificateWithPolicy
or getCertificate
.
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
Update an existing Certificate by calling updateCertificate
.
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
//Update enabled status of the certificate
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.enabled().toString()));
});
Delete an existing Certificate by calling deleteCertificate
.
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
List the certificates in the key vault by calling listCertificates
.
// 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.listCertificates()
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
Certificate Vault clients raise exceptions. For example, if you try to retrieve a certificate after it is deleted a 404
error is returned, indicating resource 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("certificateName")
} catch (ResourceNotFoundException e) {
System.out.println(e.getMessage());
}
Several KeyVault 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:
- HelloWorld.java - and HelloWorldAsync.java - Contains samples for following scenarios:
- Create a Certificate & Certificate Issuer
- Retrieve a Certificate & Certificate Issuer
- Update a Certificate
- Delete a Certificate
- ListOperations.java and ListOperationsAsync.java - Contains samples for following scenarios:
- Create a Certificate, Certificate Issuer & Certificate Contact
- List Certificates, Certificate Issuers & Certificate Contacts
- Create new version of existing certificate.
- List versions of an existing certificate.
- BackupAndRestoreOperations.java and BackupAndRestoreOperationsAsync.java - Contains samples for following scenarios:
- Create a Certificate
- Backup a Certificate -- Write it to a file.
- Delete a certificate
- Restore a certificate
- ManagingDeletedCertificates.java and ManagingDeletedCertificatesAsync.java - Contains samples for following scenarios:
- Create a Certificate
- Delete a certificate
- List deleted certificates
- Recover a deleted certificate
- Purge Deleted certificate
For more extensive documentation on Azure Key Vault, see the API reference documentation.
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 opencode@microsoft.com with any additional questions or comments.