Azure Key Vault allows you to create and store keys in the Key Vault. Azure Key Vault client supports RSA keys and elliptic curve keys, each with corresponding support in hardware security modules (HSM).
Multiple keys, and multiple versions of the same key, can be kept in the Key Vault. Cryptographic keys in Key Vault are represented as JSON Web Key [JWK] objects. This library offers operations to create, retrieve, update, delete, purge, backup, restore and list the keys 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-keys</artifactId>
<version>4.0.0-preview.1</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 KeyClient 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 --key-permissions backup delete get list set
--key-permissions: Accepted values: backup, delete, get, list, purge, recover, restore, set
-
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 KeyClient:
import com.azure.identity.credential.DefaultAzureCredential;
import com.azure.security.keyvault.keys.KeyClient;
KeyClient client = new KeyClientBuilder()
.endpoint(<your-vault-url>)
.credential(new DefaultAzureCredential())
.buildClient);
NOTE: For using Asynchronous client use KeyAsyncClient instead of KeyClient
Azure Key Vault supports multiple key types(RSA
& EC
) and algorithms, and enables the use of Hardware Security Modules (HSM) for high value keys. In addition to the key material, the following attributes may be specified:
- enabled: Specifies whether the key is enabled and useable for cryptographic operations.
- not_before: Identifies the time before which the key must not be used for cryptographic operations.
- expires: Identifies the expiration time on or after which the key MUST NOT be used for cryptographic operation.
- created: Indicates when this version of the key was created.
- updated: Indicates when this version of the key was updated.
The Key client performs the interactions with the Azure Key Vault service for getting, setting, updating, deleting, and listing keys and its versions. An asynchronous and synchronous, KeyClient, client exists in the SDK allowing for selection of a client based on an application's use case. Once you've initialized a Key, 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 Key to be stored in the Azure Key Vault.
setKey
creates a new key in the key vault. if the key with name already exists then a new version of the key is created.
import com.azure.identity.credential.DefaultAzureCredential;
import com.azure.security.keyvault.keys.models.Key;
import com.azure.security.keyvault.keys.KeyClient;
KeyClient keyClient = new KeyClientBuilder()
.endpoint(<your-vault-url>)
.credential(new DefaultAzureCredential())
.buildClient();
Key rsaKey = keyClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.expires(OffsetDateTime.now().plusYears(1))
.keySize(2048))
.value();
System.out.printf("Key is created with name %s and id %s \n", rsaKey.name(), rsaKey.id());
Key ecKey = keyClient.createEcKey(new EcKeyCreateOptions("CloudEcKey")
.curve(KeyCurveName.P_256)
.expires(OffsetDateTime.now().plusYears(1)))
.value();
System.out.printf("Key is created with name %s and id %s \n", ecKey.name(), ecKey.id());
Retrieve a previously stored Key by calling getKey
.
Key key = keyClient.getKey("key_name").value();
System.out.printf("Key is returned with name %s and id %s \n", key.name(), key.id());
Update an existing Key by calling updateKey
.
// Get the key to update.
Key key = keyClient.getKey("key_name").value();
// Update the expiry time of the key.
key.expires(OffsetDateTime.now().plusDays(30));
Key updatedKey = keyClient.updateKey(key).value();
System.out.printf("Key's updated expiry time %s \n", updatedKey.expires().toString());
Delete an existing Key by calling deleteKey
.
DeletedKey deletedKey = client.deleteKey("key_name").value();
System.out.printf("Deleted Key's deletion date %s", deletedKey.deletedDate().toString());
List the keys in the key vault by calling listKeys
.
// List operations don't return the keys with key material information. So, for each returned key we call getKey to get the key with its key material information.
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key).value();
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(), keyWithMaterial.keyMaterial().kty());
}
The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Key Service tasks, including:
- Create a Key Asynchronously
- Retrieve a Key Asynchronously
- Update an existing Key Asynchronously
- Delete a Key Asynchronously
- List Keys Asynchronously
Create a Key to be stored in the Azure Key Vault.
setKey
creates a new key in the key vault. if the key with name already exists then a new version of the key is created.
import com.azure.identity.credential.DefaultAzureCredential;
import com.azure.security.keyvault.keys.models.Key;
import com.azure.security.keyvault.keys.KeyAsyncClient;
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint(<your-vault-url>)
.credential(new DefaultAzureCredential())
.buildAsyncClient();
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.expires(OffsetDateTime.now().plusYears(1))
.keySize(2048))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.value().name(), keyResponse.value().id()));
keyAsyncClient.createEcKey(new EcKeyCreateOptions("CloudEcKey")
.expires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.value().name(), keyResponse.value().id()));
Retrieve a previously stored Key by calling getKey
.
keyAsyncClient.getKey("keyName").subscribe(keyResponse ->
System.out.printf("Key is returned with name %s and id %s \n", keyResponse.value().name(),
keyResponse.value().id()));
Update an existing Key by calling updateKey
.
keyAsyncClient.getKey("keyName").subscribe(keyResponse -> {
// Get the Key
Key key = keyResponse.value();
// Update the expiry time of the key.
key.expires(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(key).subscribe(keyResponse ->
System.out.printf("Key's updated expiry time %s \n", keyResponse.value().expires().toString()));
});
Delete an existing Key by calling deleteKey
.
keyAsyncClient.deleteKey("keyName").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's deletion time %s \n", deletedKeyResponse.value().deletedDate().toString()));
List the keys in the key vault by calling listKeys
.
// The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its // value as well.
keyAsyncClient.listKeys()
.flatMap(keyAsyncClient::getKey).subscribe(keyResponse ->
System.out.printf("Key returned with name %s and id %s \n", keyResponse.value().name(), keyResponse.value().id()));
Key Vault clients raise exceptions. For example, if you try to retrieve a key 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 {
keyClient.getKey("deletedKey")
} 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 Key
- Retrieve a Key
- Update a Key
- Delete a Key
- ListOperations.java and ListOperationsAsync.java - Contains samples for following scenarios:
- Create a Key
- List Keys
- Create new version of existing key.
- List versions of an existing key.
- BackupAndRestoreOperations.java and BackupAndRestoreOperationsAsync.java - Contains samples for following scenarios:
- Create a Key
- Backup a Key -- Write it to a file.
- Delete a key
- Restore a key
- ManagingDeletedKeys.java and ManagingDeletedKeysAsync.java - Contains samples for following scenarios:
- Create a Key
- Delete a key
- List deleted keys
- Recover a deleted key
- Purge Deleted key
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 [email protected] with any additional questions or comments.