com.azure.security.keyvault.keys.KeyAsyncClient Maven / Gradle / Ivy
Show all versions of azure-security-keyvault-keys Show documentation
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.keys;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.PollingContext;
import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient;
import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder;
import com.azure.security.keyvault.keys.implementation.KeyClientImpl;
import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils;
import com.azure.security.keyvault.keys.implementation.models.DeletedKeyItem;
import com.azure.security.keyvault.keys.implementation.models.KeyItem;
import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException;
import com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils;
import com.azure.security.keyvault.keys.models.CreateEcKeyOptions;
import com.azure.security.keyvault.keys.models.CreateKeyOptions;
import com.azure.security.keyvault.keys.models.CreateOctKeyOptions;
import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions;
import com.azure.security.keyvault.keys.models.DeletedKey;
import com.azure.security.keyvault.keys.models.ImportKeyOptions;
import com.azure.security.keyvault.keys.models.JsonWebKey;
import com.azure.security.keyvault.keys.models.KeyCurveName;
import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm;
import com.azure.security.keyvault.keys.models.KeyOperation;
import com.azure.security.keyvault.keys.models.KeyProperties;
import com.azure.security.keyvault.keys.models.KeyRotationPolicy;
import com.azure.security.keyvault.keys.models.KeyType;
import com.azure.security.keyvault.keys.models.KeyVaultKey;
import com.azure.security.keyvault.keys.models.ReleaseKeyOptions;
import com.azure.security.keyvault.keys.models.ReleaseKeyResult;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static com.azure.core.util.FluxUtil.monoError;
import static com.azure.core.util.FluxUtil.withContext;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createDeletedKey;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyAttributes;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyVaultKey;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.mapJsonWebKey;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.mapKeyReleasePolicy;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.mapKeyRotationPolicy;
import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.mapKeyRotationPolicyImpl;
/**
* The {@link KeyAsyncClient} provides asynchronous methods to manage {@link KeyVaultKey keys} in the Azure Key Vault.
* The client supports creating, retrieving, updating, deleting, purging, backing up, restoring, listing, releasing
* and rotating the {@link KeyVaultKey keys}. The client also supports listing {@link DeletedKey deleted keys} for a
* soft-delete enabled key vault.
*
* Getting Started
*
* In order to interact with the Azure Key Vault service, you will need to create an instance of the
* {@link KeyAsyncClient} class, a vault url and a credential object.
*
* The examples shown in this document use a credential object named DefaultAzureCredential for authentication,
* which is appropriate for most scenarios, including local development and production environments. Additionally,
* we recommend using a
*
* managed identity for authentication in production environments.
* You can find more information on different ways of authenticating and their corresponding credential types in the
*
* Azure Identity documentation".
*
* Sample: Construct Asynchronous Key Client
*
* The following code sample demonstrates the creation of a {@link KeyAsyncClient}, using the
* {@link KeyClientBuilder} to configure it.
*
*
*
* KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
* .vaultUrl("<your-key-vault-url>")
* .credential(new DefaultAzureCredentialBuilder().build())
* .buildAsyncClient();
*
*
*
*
*
*
*
* Create a Cryptographic Key
* The {@link KeyAsyncClient} can be used to create a key in the key vault.
*
* Code Sample:
* The following code sample demonstrates how to asynchronously create a cryptographic key in the key vault,
* using the {@link KeyAsyncClient#createKey(String, KeyType)} API.
*
*
*
* keyAsyncClient.createKey("keyName", KeyType.EC)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(key ->
* System.out.printf("Created key with name: %s and id: %s %n", key.getName(),
* key.getId()));
*
*
*
* Note: For the synchronous sample, refer to {@link KeyClient}.
*
*
*
*
*
* Get a Cryptographic Key
* The {@link KeyAsyncClient} can be used to retrieve a key from the key vault.
*
* Code Sample:
* The following code sample demonstrates how to asynchronously retrieve a key from the key vault, using
* the {@link KeyAsyncClient#getKey(String)} API.
*
*
*
* keyAsyncClient.getKey("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(key ->
* System.out.printf("Created key with name: %s and: id %s%n", key.getName(),
* key.getId()));
*
*
*
* Note: For the synchronous sample, refer to {@link KeyClient}.
*
*
*
*
*
* Delete a Cryptographic Key
* The {@link KeyAsyncClient} can be used to delete a key from the key vault.
*
* Code Sample:
* The following code sample demonstrates how to asynchronously delete a key from the
* key vault, using the {@link KeyAsyncClient#beginDeleteKey(String)} API.
*
*
*
* keyAsyncClient.beginDeleteKey("keyName")
* .subscribe(pollResponse -> {
* System.out.printf("Deletion status: %s%n", pollResponse.getStatus());
* System.out.printf("Key name: %s%n", pollResponse.getValue().getName());
* System.out.printf("Key delete date: %s%n", pollResponse.getValue().getDeletedOn());
* });
*
*
*
* Note: For the synchronous sample, refer to {@link KeyClient}.
*
* @see com.azure.security.keyvault.keys
* @see KeyClientBuilder
*/
@ServiceClient(builder = KeyClientBuilder.class, isAsync = true,
serviceInterfaces = KeyClientImpl.KeyClientService.class)
public final class KeyAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(KeyAsyncClient.class);
private final KeyClientImpl implClient;
private final String vaultUrl;
private final KeyServiceVersion serviceVersion;
/**
* Creates a {@link KeyAsyncClient} that uses a {@link KeyClientImpl} to service requests.
*
* @param implClient the impl client.
* @param vaultUrl the vault url.
* @param keyServiceVersion the service version.
*/
KeyAsyncClient(KeyClientImpl implClient, String vaultUrl, KeyServiceVersion keyServiceVersion) {
this.implClient = implClient;
this.vaultUrl = vaultUrl;
this.serviceVersion = keyServiceVersion;
}
/**
* Get the vault endpoint url to which service requests are sent to.
*
* @return The vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The {@link HttpPipeline pipeline}.
*/
HttpPipeline getHttpPipeline() {
return implClient.getHttpPipeline();
}
/**
* Creates a {@link CryptographyAsyncClient} for the latest version of a given key.
*
* To ensure correct behavior when performing operations such as {@code Decrypt}, {@code Unwrap} and
* {@code Verify}, it is recommended to use a {@link CryptographyAsyncClient} created for the specific key
* version that was used for the corresponding inverse operation: {@code Encrypt}, {@code Wrap}, or
* {@code Sign}, respectively.
*
* You can provide a key version either via {@link KeyAsyncClient#getCryptographyAsyncClient(String, String)} or
* by ensuring it is included in the {@code keyIdentifier} passed to
* {@link CryptographyClientBuilder#keyIdentifier(String)} before building a client.
*
* @param keyName The name of the key.
*
* @return An instance of {@link CryptographyAsyncClient} associated with the latest version of a key with the
* provided name.
*
* @throws IllegalArgumentException If {@code keyName} is {@code null} or empty.
*/
public CryptographyAsyncClient getCryptographyAsyncClient(String keyName) {
return getCryptographyAsyncClient(keyName, null);
}
/**
* Creates a {@link CryptographyAsyncClient} for a given key version.
*
* @param keyName The name of the key.
* @param keyVersion The key version.
*
* @return An instance of {@link CryptographyAsyncClient} associated with a key with the provided name and version.
* If {@code keyVersion} is {@code null} or empty, the client will use the latest version of the key.
*
* @throws IllegalArgumentException If {@code keyName} is {@code null} or empty.
*/
public CryptographyAsyncClient getCryptographyAsyncClient(String keyName, String keyVersion) {
return KeyVaultKeysUtils.getCryptographyClientBuilder(keyName, keyVersion, vaultUrl, getHttpPipeline(),
serviceVersion).buildAsyncClient();
}
/**
* Creates a new {@link KeyVaultKey key} and stores it in the key vault. The create key operation can be used to
* create any {@link KeyType keyType} in Azure Key Vault. If a {@link KeyVaultKey key} with the provided name
* already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires the
* {@code keys/create} permission.
*
* The {@link KeyType keyType} indicates the type of {@link KeyVaultKey key} to create. Possible values include:
* {@link KeyType#EC EC}, {@link KeyType#EC_HSM EC-HSM}, {@link KeyType#RSA RSA}, {@link KeyType#RSA_HSM RSA-HSM},
* {@link KeyType#OCT OCT}, and {@link KeyType#OCT_HSM OCT-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey EC key}. Subscribes to the call asynchronously and prints out the newly
* {@link KeyVaultKey created key} details when a response has been received.
*
*
* keyAsyncClient.createKey("keyName", KeyType.EC)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(key ->
* System.out.printf("Created key with name: %s and id: %s %n", key.getName(),
* key.getId()));
*
*
*
* @param name The name of the {@link KeyVaultKey key} being created.
* @param keyType The type of {@link KeyVaultKey key} to create. For valid values, see {@link KeyType KeyType}.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@code name} is an empty string.
* @throws NullPointerException If {@code name} or {@code keyType} are {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono createKey(String name, KeyType keyType) {
return createKeyWithResponse(new CreateKeyOptions(name, keyType)).flatMap(FluxUtil::toMono);
}
/**
* Creates a new {@link KeyVaultKey key} and stores it in the key vault. The create key operation can be used to
* create any {@link KeyType keyType} in Azure Key Vault. If a {@link KeyVaultKey key} with the provided name
* already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires the
* {@code keys/create} permission.
*
* The {@link KeyType keyType} indicates the type of {@link KeyVaultKey key} to create. Possible values include:
* {@link KeyType#EC EC}, {@link KeyType#EC_HSM EC-HSM}, {@link KeyType#RSA RSA}, {@link KeyType#RSA_HSM RSA-HSM},
* {@link KeyType#OCT OCT}, and {@link KeyType#OCT_HSM OCT-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey EC key}. Subscribes to the call asynchronously and prints out the newly
* {@link KeyVaultKey created key} details when a response has been received.
*
*
*
* CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA)
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createKeyWithResponse(createKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(createKeyResponse ->
* System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(),
* createKeyResponse.getValue().getId()));
*
*
*
* @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the
* {@link KeyVaultKey key} being created.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code createKeyOptions} is null.
* @throws ResourceModifiedException If {@code createKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
if (createKeyOptions == null) {
return monoError(LOGGER, new NullPointerException("'createKeyOptions' cannot be null."));
}
return implClient.createKeyWithResponseAsync(vaultUrl, createKeyOptions.getName(),
createKeyOptions.getKeyType(), null, null, createKeyOptions.getKeyOperations(),
createKeyAttributes(createKeyOptions), createKeyOptions.getTags(), null,
mapKeyReleasePolicy(createKeyOptions.getReleasePolicy()))
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapCreateKeyException(KeyVaultErrorException exception) {
return (exception.getResponse().getStatusCode() == 400)
? new ResourceModifiedException(exception.getMessage(), exception.getResponse(), exception.getValue())
: exception;
}
/**
* Creates a new {@link KeyVaultKey key} and stores it in the key vault. The create key operation can be used to
* create any {@link KeyType keyType} in Azure Key Vault. If a {@link KeyVaultKey key} with the provided name
* already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires the
* {@code keys/create} permission.
*
* The {@link CreateKeyOptions} parameter is required. The {@link CreateKeyOptions#getExpiresOn() expires} and
* {@link CreateKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not specified.
*
*
* The {@link CreateKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey key} to create.
* Possible values include: {@link KeyType#EC EC}, {@link KeyType#EC_HSM EC-HSM}, {@link KeyType#RSA RSA},
* {@link KeyType#RSA_HSM RSA-HSM}, {@link KeyType#OCT OCT}, and {@link KeyType#OCT_HSM OCT-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey RSA key} which activates in one day and expires in one year. Subscribes to
* the call asynchronously and prints out the newly {@link KeyVaultKey created key} details when a response has been
* received.
*
*
* CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA)
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createKey(createKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(key ->
* System.out.printf("Created key with name: %s and id: %s %n", key.getName(),
* key.getId()));
*
*
*
* @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the
* {@link KeyVaultKey key} being created.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code createKeyOptions} is {@code null}.
* @throws ResourceModifiedException If {@code createKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono createKey(CreateKeyOptions createKeyOptions) {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
}
/**
* /**
* Creates a new {@link KeyVaultKey RSA key} and stores it in the key vault. The create RSA key operation can be
* used to create any RSA key type in Azure Key Vault. If a {@link KeyVaultKey key} with the provided name already
* exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires the
* {@code keys/create} permission.
*
* The {@link CreateRsaKeyOptions} parameter is required. The {@link CreateRsaKeyOptions#getKeySize() keySize}
* can be optionally specified. The {@link CreateRsaKeyOptions#getExpiresOn() expires} and
* {@link CreateRsaKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateRsaKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not
* specified.
*
* The {@link CreateRsaKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey key} to create.
* Possible values include: {@link KeyType#RSA RSA} and {@link KeyType#RSA_HSM RSA-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey RSA key} with size 2048 which activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly {@link KeyVaultKey created key} details when a
* response has been received.
*
*
* CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName")
* .setKeySize(2048)
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createRsaKey(createRsaKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(rsaKey ->
* System.out.printf("Created key with name: %s and id: %s %n", rsaKey.getName(),
* rsaKey.getId()));
*
*
*
* @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the
* {@link KeyVaultKey RSA key} being created.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateRsaKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code createRsaKeyOptions} is {@code null}.
* @throws ResourceModifiedException If {@code createRsaKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
}
/**
* Creates a new {@link KeyVaultKey RSA key} and stores it in the key vault. The create RSA key operation can be
* used to create any RSA key type in Azure Key Vault. If a {@link KeyVaultKey key} with the provided name already
* exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires the
* {@code keys/create} permission.
*
* The {@link CreateRsaKeyOptions} parameter is required. The {@link CreateRsaKeyOptions#getKeySize() keySize}
* can be optionally specified. The {@link CreateRsaKeyOptions#getExpiresOn() expires} and
* {@link CreateRsaKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateRsaKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not
* specified.
*
* The {@link CreateRsaKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey key} to create.
* Possible values include: {@link KeyType#RSA RSA} and {@link KeyType#RSA_HSM RSA-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey RSA key} with size 2048 which activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly {@link KeyVaultKey created key} details when a
* response has been received.
*
*
* CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName")
* .setKeySize(2048)
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createRsaKeyWithResponse(createRsaKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(createRsaKeyResponse ->
* System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(),
* createRsaKeyResponse.getValue().getId()));
*
*
*
* @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the
* {@link KeyVaultKey RSA key} being created.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateRsaKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code createRsaKeyOptions} is {@code null}.
* @throws ResourceModifiedException If {@code createRsaKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
if (createRsaKeyOptions == null) {
return monoError(LOGGER, new NullPointerException("'createRsaKeyOptions' cannot be null."));
}
return implClient.createKeyWithResponseAsync(vaultUrl, createRsaKeyOptions.getName(),
createRsaKeyOptions.getKeyType(), createRsaKeyOptions.getKeySize(),
createRsaKeyOptions.getPublicExponent(), createRsaKeyOptions.getKeyOperations(),
createKeyAttributes(createRsaKeyOptions), createRsaKeyOptions.getTags(), null,
mapKeyReleasePolicy(createRsaKeyOptions.getReleasePolicy()))
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Creates a new {@link KeyVaultKey EC key} and stores it in the key vault. The create EC key operation can be
* used to create any EC {@link KeyType key type} in Azure Key Vault. If a {@link KeyVaultKey key} with the
* provided name already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires
* the {@code keys/create} permission.
*
* The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions#getCurveName() key curve}
* can be optionally specified. If not specified, the default value {@link KeyCurveName#P_256 P-256} is used by
* Azure Key Vault. The {@link CreateEcKeyOptions#getExpiresOn() expires} and
* {@link CreateEcKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateEcKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not specified.
*
*
* The {@link CreateEcKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey} key to create.
* Possible values include: {@link KeyType#EC EC} and {@link KeyType#EC_HSM EC-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey EC key} with a {@link KeyCurveName#P_384 P-384} web key curve. The key
* activates in one day and expires in one year. Subscribes to the call asynchronously and prints out the newly
* {@link KeyVaultKey created key} details when a response has been received.
*
*
* CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName")
* .setCurveName(KeyCurveName.P_384)
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createEcKey(createEcKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(ecKey ->
* System.out.printf("Created key with name: %s and id: %s %n", ecKey.getName(),
* ecKey.getId()));
*
*
*
* @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the
* {@link KeyVaultKey EC key} being created.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateEcKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException If {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono createEcKey(CreateEcKeyOptions createEcKeyOptions) {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
}
/**
* Creates a new {@link KeyVaultKey EC key} and stores it in the key vault. The create EC key operation can be
* used to create any EC {@link KeyType key type} in Azure Key Vault. If a {@link KeyVaultKey key} with the
* provided name already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. It requires
* the {@code keys/create} permission.
*
* The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions#getCurveName() key curve}
* can be optionally specified. If not specified, the default value {@link KeyCurveName#P_256 P-256} is used by
* Azure Key Vault. The {@link CreateEcKeyOptions#getExpiresOn() expires} and
* {@link CreateEcKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateEcKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not
* specified.
*
*
* The {@link CreateEcKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey} key to create.
* Possible values include: {@link KeyType#EC EC} and {@link KeyType#EC_HSM EC-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey EC key} with a {@link KeyCurveName#P_384 P-384} web key curve. The key
* activates in one day and expires in one year. Subscribes to the call asynchronously and prints out the newly
* {@link KeyVaultKey created key} details when a response has been received.
*
*
* CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName")
* .setCurveName(KeyCurveName.P_384)
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createEcKeyWithResponse(createEcKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(createEcKeyResponse ->
* System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(),
* createEcKeyResponse.getValue().getId()));
*
*
*
* @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the
* {@link KeyVaultKey EC key} being created.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateEcKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException If {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
if (createEcKeyOptions == null) {
return monoError(LOGGER, new NullPointerException("'createEcKeyOptions' cannot be null."));
}
return implClient.createKeyWithResponseAsync(vaultUrl, createEcKeyOptions.getName(),
createEcKeyOptions.getKeyType(), null, null, createEcKeyOptions.getKeyOperations(),
createKeyAttributes(createEcKeyOptions), createEcKeyOptions.getTags(),
createEcKeyOptions.getCurveName(), mapKeyReleasePolicy(createEcKeyOptions.getReleasePolicy()))
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Creates and stores a new {@link KeyVaultKey symmetric key} in the key vault. If a {@link KeyVaultKey key} with
* the provided name already exists, Azure Key Vault creates a new version of the key. This operation requires
* the {@code keys/create} permission.
*
* The {@link CreateOctKeyOptions} parameter is required. The {@link CreateOctKeyOptions#getExpiresOn() expires}
* and {@link CreateOctKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateOctKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not
* specified.
*
* The {@link CreateOctKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey} key to create.
* Possible values include: {@link KeyType#OCT OCT} and {@link KeyType#OCT_HSM OCT-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey symmetric key}. The {@link KeyVaultKey key} activates in one day and expires
* in one year. Subscribes to the call asynchronously and prints out the details of the newly
* {@link KeyVaultKey created key} when a response has been received.
*
*
* CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName")
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createOctKey(createOctKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(octKey ->
* System.out.printf("Created key with name: %s and id: %s %n", octKey.getName(),
* octKey.getId()));
*
*
*
* @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the
* {@link KeyVaultKey symmetric key} being created.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateOctKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException If {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono createOctKey(CreateOctKeyOptions createOctKeyOptions) {
return createOctKeyWithResponse(createOctKeyOptions).flatMap(FluxUtil::toMono);
}
/**
* Creates and stores a new {@link KeyVaultKey symmetric key} in the key vault. If a {@link KeyVaultKey key} with
* the provided name already exists, Azure Key Vault creates a new version of the key. This operation requires
* the {@code keys/create} permission.
*
* The {@link CreateOctKeyOptions} parameter is required. The {@link CreateOctKeyOptions#getExpiresOn() expires}
* and {@link CreateOctKeyOptions#getNotBefore() notBefore} values are optional. The
* {@link CreateOctKeyOptions#isEnabled() enabled} field is set to {@code true} by Azure Key Vault, if not
* specified.
*
* The {@link CreateOctKeyOptions#getKeyType() keyType} indicates the type of {@link KeyVaultKey} key to create.
* Possible values include: {@link KeyType#OCT OCT} and {@link KeyType#OCT_HSM OCT-HSM}.
*
* Code Samples
* Creates a new {@link KeyVaultKey symmetric key}. The {@link KeyVaultKey key} activates in one day and expires
* in one year. Subscribes to the call asynchronously and prints out the details of the newly
* {@link KeyVaultKey created key} when a response has been received.
*
*
* CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName")
* .setNotBefore(OffsetDateTime.now().plusDays(1))
* .setExpiresOn(OffsetDateTime.now().plusYears(1));
*
* keyAsyncClient.createOctKeyWithResponse(createOctKeyOptions)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(createOctKeyResponse ->
* System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(),
* createOctKeyResponse.getValue().getId()));
*
*
*
* @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the
* {@link KeyVaultKey symmetric key} being created.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey created key}.
*
* @throws HttpResponseException If {@link CreateOctKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code createOctKeyOptions} is {@code null}.
* @throws ResourceModifiedException If {@code createOctKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions) {
try {
if (createOctKeyOptions == null) {
return monoError(LOGGER, new NullPointerException("'createOctKeyOptions' cannot be null."));
}
return implClient.createKeyWithResponseAsync(vaultUrl, createOctKeyOptions.getName(),
createOctKeyOptions.getKeyType(), createOctKeyOptions.getKeySize(), null,
createOctKeyOptions.getKeyOperations(), createKeyAttributes(createOctKeyOptions),
createOctKeyOptions.getTags(), null, mapKeyReleasePolicy(createOctKeyOptions.getReleasePolicy()))
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Imports an externally created {@link JsonWebKey key} and stores it in the key vault. The import key operation
* may be used to import any {@link KeyType key type} into Azure Key Vault. If a {@link KeyVaultKey key} with
* the provided name already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. This
* operation requires the {@code keys/import} permission.
*
* Code Samples
* Imports a new {@link KeyVaultKey key} into key vault. Subscribes to the call asynchronously and prints out the
* newly {@link KeyVaultKey imported key} details when a response has been received.
*
*
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport)
* .subscribe(keyVaultKey ->
* System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(),
* keyVaultKey.getId()));
*
*
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey imported key}.
*
* @throws HttpResponseException If {@code name} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono importKey(String name, JsonWebKey keyMaterial) {
return importKeyWithResponse(new ImportKeyOptions(name, keyMaterial)).flatMap(FluxUtil::toMono);
}
/**
* Imports an externally created {@link JsonWebKey key} and stores it in the key vault. The import key operation
* may be used to import any {@link KeyType key type} into Azure Key Vault. If a {@link KeyVaultKey key} with
* the provided name already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. This
* operation requires the {@code keys/import} permission.
*
* {@link ImportKeyOptions} is required and its fields {@link ImportKeyOptions#getName() name} and
* {@link ImportKeyOptions#getKey() key material} cannot be {@code null}. The
* {@link ImportKeyOptions#getExpiresOn() expires} and {@link ImportKeyOptions#getNotBefore() notBefore} values
* in {@code keyImportOptions} are optional. If not specified, no values are set for the fields. The
* {@link ImportKeyOptions#isEnabled() enabled} field is set to {@code true} and the
* {@link ImportKeyOptions#isHardwareProtected() hsm} field is set to {@code false} by Azure Key Vault, if they are
* not specified.
*
* Code Samples
* Imports a new {@link KeyVaultKey key} into key vault. Subscribes to the call asynchronously and prints out the
* newly {@link KeyVaultKey imported key} details when a response has been received.
*
*
* ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport)
* .setHardwareProtected(false);
*
* keyAsyncClient.importKey(options).subscribe(keyVaultKey ->
* System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), keyVaultKey.getId()));
*
*
*
* @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the
* {@link JsonWebKey} being imported.
*
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
*
* @throws HttpResponseException If {@link ImportKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code importKeyOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono importKey(ImportKeyOptions importKeyOptions) {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
}
/**
* Imports an externally created {@link JsonWebKey key} and stores it in the key vault. The import key operation
* may be used to import any {@link KeyType key type} into Azure Key Vault. If a {@link KeyVaultKey key} with
* the provided name already exists, Azure Key Vault creates a new version of the {@link KeyVaultKey key}. This
* operation requires the {@code keys/import} permission.
*
* {@link ImportKeyOptions} is required and its fields {@link ImportKeyOptions#getName() name} and
* {@link ImportKeyOptions#getKey() key material} cannot be {@code null}. The
* {@link ImportKeyOptions#getExpiresOn() expires} and {@link ImportKeyOptions#getNotBefore() notBefore} values
* in {@code keyImportOptions} are optional. If not specified, no values are set for the fields. The
* {@link ImportKeyOptions#isEnabled() enabled} field is set to {@code true} and the
* {@link ImportKeyOptions#isHardwareProtected() hsm} field is set to {@code false} by Azure Key Vault, if they are
* not specified.
*
* Code Samples
* Imports a new {@link KeyVaultKey key} into key vault. Subscribes to the call asynchronously and prints out the
* newly {@link KeyVaultKey imported key} details when a response has been received.
*
*
* ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport)
* .setHardwareProtected(false);
*
* keyAsyncClient.importKeyWithResponse(importKeyOptions).subscribe(response ->
* System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(),
* response.getValue().getId()));
*
*
*
* @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the
* {@link JsonWebKey} being imported.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey imported key}.
*
* @throws HttpResponseException If {@link ImportKeyOptions#getName()} is an empty string.
* @throws NullPointerException If {@code importKeyOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
if (importKeyOptions == null) {
return monoError(LOGGER, new RuntimeException("'importKeyOptions' cannot be null."));
}
return implClient.importKeyWithResponseAsync(vaultUrl, importKeyOptions.getName(),
mapJsonWebKey(importKeyOptions.getKey()), importKeyOptions.isHardwareProtected(),
createKeyAttributes(importKeyOptions), importKeyOptions.getTags(),
mapKeyReleasePolicy(importKeyOptions.getReleasePolicy()))
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Gets the public part of the specified {@link KeyVaultKey key} and key version. The get key operation is
* applicable to all {@link KeyType key types} and it requires the {@code keys/get} permission.
*
* Code Samples
* Gets a specific version of the {@link KeyVaultKey key} in the key vault. Subscribes to the call asynchronously
* and prints out the {@link KeyVaultKey retrieved key} details when a response has been received.
*
*
* String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
*
* keyAsyncClient.getKey("keyName", keyVersion)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(key ->
* System.out.printf("Created key with name: %s and: id %s%n", key.getName(),
* key.getId()));
*
*
*
* @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}.
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient#getKey(String)}, with the latest version being retrieved.
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* The content of the key is {@code null} if both {@code name} and {@code version} are {@code null} or empty.
*
* @throws HttpResponseException If a valid {@code name} and a non null/empty {@code version} is specified.
* @throws ResourceNotFoundException When a {@link KeyVaultKey key} with the provided {@code name} doesn't exist in
* the key vault or an empty/{@code null} {@code name} and a non-null/empty {@code version} is provided.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono getKey(String name, String version) {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
}
/**
* Gets the public part of the specified {@link KeyVaultKey key} and key version. The get key operation is
* applicable to all {@link KeyType key types} and it requires the {@code keys/get} permission.
*
* Code Samples
* Gets a specific version of the {@link KeyVaultKey key} in the key vault. Subscribes to the call asynchronously
* and prints out the {@link KeyVaultKey retrieved key} details when a response has been received.
*
*
* String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
*
* keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(getKeyResponse ->
* System.out.printf("Created key with name: %s and: id %s%n",
* getKeyResponse.getValue().getName(), getKeyResponse.getValue().getId()));
*
*
*
* @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}.
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient#getKey(String)}, with the latest version being retrieved.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* requested {@link KeyVaultKey key}. The content of the key is {@code null} if both {@code name} and
* {@code version} are {@code null} or empty.
*
* @throws HttpResponseException If a valid {@code name} and a non-null/empty {@code version} is specified.
* @throws ResourceNotFoundException When a {@link KeyVaultKey key} with the provided {@code name} doesn't exist in
* the key vault or an empty/{@code null} {@code name} and a non-null/empty {@code version} is provided.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> getKeyWithResponse(String name, String version) {
try {
return implClient.getKeyWithResponseAsync(vaultUrl, name, version)
.onErrorMap(KeyVaultErrorException.class, KeyVaultKeysUtils::mapGetKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Gets the public part of the specified {@link KeyVaultKey key} and key version. The get key operation is
* applicable to all {@link KeyType key types} and it requires the {@code keys/get} permission.
*
* Code Samples
* Gets a specific version of the {@link KeyVaultKey key} in the key vault. Subscribes to the call asynchronously
* and prints out the {@link KeyVaultKey retrieved key} details when a response has been received.
*
*
* keyAsyncClient.getKey("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(key ->
* System.out.printf("Created key with name: %s and: id %s%n", key.getName(),
* key.getId()));
*
*
*
* @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}.
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is {@code null}
* if {@code name} is {@code null} or empty.
*
* @throws HttpResponseException If a valid {@code name} and a non-null/empty {@code version} is specified.
* @throws ResourceNotFoundException When a {@link KeyVaultKey key} with the provided {@code name} doesn't exist in
* the key vault or an empty/{@code null} {@code name} and a non-null/empty {@code version} is provided.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono getKey(String name) {
return getKeyWithResponse(name, null).flatMap(FluxUtil::toMono);
}
/**
* Updates the {@link KeyProperties attributes} and {@link KeyOperation key operations} associated with the
* specified {@link KeyVaultKey key}, but not the cryptographic key material of the specified
* {@link KeyVaultKey key} in the key vault. The update operation changes specified
* {@link KeyProperties attributes} of an existing stored {@link KeyVaultKey key} and
* {@link KeyProperties attributes} that are not specified in the request are left unchanged. The cryptographic
* key material of a {@link KeyVaultKey key} itself cannot be changed. This operation requires the
* {@code keys/set} permission.
*
* Code Samples
* Gets latest version of the {@link KeyVaultKey key}, changes its notBefore time and then updates it in the
* Azure Key Vault. Subscribes to the call asynchronously and prints out the {@link KeyVaultKey returned key}
* details when a response has been received.
*
*
* keyAsyncClient.getKey("keyName")
* .subscribe(getKeyResponse -> {
* //Update the not before time of the key.
* getKeyResponse.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50));
* keyAsyncClient.updateKeyPropertiesWithResponse(getKeyResponse.getProperties(), KeyOperation.ENCRYPT,
* KeyOperation.DECRYPT)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(updateKeyResponse ->
* System.out.printf("Updated key's \"not before time\": %s%n",
* updateKeyResponse.getValue().getProperties().getNotBefore().toString()));
* });
*
*
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated {@link KeyOperation key operations} to associate with the key.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey updated key}.
*
* @throws HttpResponseException If {@link KeyProperties#getName() name} or
* {@link KeyProperties#getVersion() version} is an empty string.
* @throws NullPointerException If {@code keyProperties} is null.
* @throws ResourceNotFoundException When a key with {@link KeyProperties#getName() name} and
* {@link KeyProperties#getVersion() version} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> updateKeyPropertiesWithResponse(KeyProperties keyProperties,
KeyOperation... keyOperations) {
try {
if (keyProperties == null) {
return monoError(LOGGER, new NullPointerException("'keyProperties' cannot be null."));
}
return implClient.updateKeyWithResponseAsync(vaultUrl, keyProperties.getName(), keyProperties.getVersion(),
keyOperations == null ? null : Arrays.asList(keyOperations), createKeyAttributes(keyProperties),
keyProperties.getTags(), mapKeyReleasePolicy(keyProperties.getReleasePolicy()))
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Updates the {@link KeyProperties attributes} and {@link KeyOperation key operations} associated with the
* specified {@link KeyVaultKey key}, but not the cryptographic key material of the specified
* {@link KeyVaultKey key} in the key vault. The update operation changes specified
* {@link KeyProperties attributes} of an existing stored {@link KeyVaultKey key} and
* {@link KeyProperties attributes} that are not specified in the request are left unchanged. The cryptographic
* key material of a {@link KeyVaultKey key} itself cannot be changed. This operation requires the
* {@code keys/set} permission.
*
* Code Samples
* Gets latest version of the {@link KeyVaultKey key}, changes its notBefore time and then updates it in the
* Azure Key Vault. Subscribes to the call asynchronously and prints out the {@link KeyVaultKey returned key}
* details when a response has been received.
*
*
* keyAsyncClient.getKey("keyName")
* .subscribe(key -> {
* //Update the not before time of the key.
* key.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50));
* keyAsyncClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT,
* KeyOperation.DECRYPT)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(updatedKey ->
* System.out.printf("Updated key's \"not before time\": %s%n",
* updatedKey.getProperties().getNotBefore().toString()));
* });
*
*
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated {@link KeyOperation key operations} to associate with the key.
*
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
*
* @throws HttpResponseException If {@link KeyProperties#getName() name} or
* {@link KeyProperties#getVersion() version} is an empty string.
* @throws NullPointerException If {@code key} is {@code null}.
* @throws ResourceNotFoundException When a key with {@link KeyProperties#getName() name} and
* {@link KeyProperties#getVersion() version} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
}
/**
* Deletes a {@link KeyVaultKey key} of any type from the key vault. If soft-delete is enabled on the key vault then
* the {@link KeyVaultKey key} is placed in the deleted state and requires to be purged for permanent deletion
* else the {@link KeyVaultKey key} is permanently deleted. The delete operation applies to any
* {@link KeyVaultKey key} stored in Azure Key Vault but it cannot be applied to an individual version
* of a {@link KeyVaultKey key}. This operation removes the cryptographic material associated with the
* {@link KeyVaultKey key}, which means the {@link KeyVaultKey key} is not usable for {@code Sign/Verify},
* {@code Wrap/Unwrap} or {@code Encrypt/Decrypt} operations. This operation requires the {@code keys/delete}
* permission.
*
* Code Samples
* Deletes the {@link KeyVaultKey key} in the Azure Key Vault. Subscribes to the call asynchronously and prints
* out the {@link KeyVaultKey deleted key} details when a response has been received.
*
*
* keyAsyncClient.beginDeleteKey("keyName")
* .subscribe(pollResponse -> {
* System.out.printf("Deletion status: %s%n", pollResponse.getStatus());
* System.out.printf("Key name: %s%n", pollResponse.getValue().getName());
* System.out.printf("Key delete date: %s%n", pollResponse.getValue().getDeletedOn());
* });
*
*
*
* @param name The name of the {@link KeyVaultKey key} to be deleted.
*
* @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux beginDeleteKey(String name) {
return new PollerFlux<>(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name),
(context, firstResponse) -> Mono.empty(), context -> Mono.empty());
}
private Function, Mono> deleteActivationOperation(String name) {
return pollingContext -> implClient.deleteKeyAsync(vaultUrl, name)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapDeleteKeyException)
.map(KeyVaultKeysModelsUtils::createDeletedKey);
}
static HttpResponseException mapDeleteKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
private Function, Mono>> deletePollOperation(String name) {
return pollingContext -> implClient.getDeletedKeyAsync(vaultUrl, name)
.map(bundle -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
createDeletedKey(bundle)))
.onErrorResume(HttpResponseException.class, ex -> {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue()));
} else {
// This means either vault has soft-delete disabled or permission is not granted for the get deleted key
// operation. In both cases deletion operation was successful when activation operation succeeded before
// reaching here.
return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue()));
}
})
// This means either vault has soft-delete disabled or permission is not granted for the get deleted key
// operation. In both cases deletion operation was successful when activation operation succeeded before
// reaching here.
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue()));
}
/**
* Gets the public part of a {@link KeyVaultKey deleted key}. The get deleted Key operation is applicable for
* soft-delete enabled vaults. This operation requires the {@code keys/get} permission.
*
* Code Samples
* Gets the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the call
* asynchronously and prints out the {@link KeyVaultKey deleted key} details when a response has been received.
*
*
* keyAsyncClient.getDeletedKey("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(deletedKey ->
* System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()));
*
*
*
* @param name The name of the deleted {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono getDeletedKey(String name) {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
}
/**
* Gets the public part of a {@link KeyVaultKey deleted key}. The get deleted Key operation is applicable for
* soft-delete enabled vaults. This operation requires the {@code keys/get} permission.
*
* Code Samples
* Gets the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the call
* asynchronously and prints out the {@link KeyVaultKey deleted key} details when a response has been received.
*
*
* keyAsyncClient.getDeletedKeyWithResponse("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(getDeletedKeyResponse ->
* System.out.printf("Deleted key's recovery id: %s%n", getDeletedKeyResponse.getValue().getRecoveryId()));
*
*
*
* @param name The name of the deleted {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link DeletedKey deleted key}.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> getDeletedKeyWithResponse(String name) {
try {
return implClient.getDeletedKeyWithResponseAsync(vaultUrl, name)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapGetDeletedKeyException)
.map(response -> new SimpleResponse<>(response, createDeletedKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapGetDeletedKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* Permanently deletes the specified {@link KeyVaultKey key} without the possibility of recovery. The purge
* deleted key operation is applicable for soft-delete enabled vaults. This operation requires the
* {@code keys/purge} permission.
*
* Code Samples
* Purges the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the call
* asynchronously and prints out the status code from the server response when a response has been received.
*
*
* keyAsyncClient.purgeDeletedKey("deletedKeyName")
* .subscribe(ignored ->
* System.out.println("Successfully purged deleted key"));
*
*
*
* @param name The name of the {@link KeyVaultKey deleted key}.
*
* @return An empty {@link Mono}.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono purgeDeletedKey(String name) {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
}
/**
* Permanently deletes the specified {@link KeyVaultKey key} without the possibility of recovery. The purge
* deleted key operation is applicable for soft-delete enabled vaults. This operation requires the
* {@code keys/purge} permission.
*
* Code Samples
* Purges the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the call
* asynchronously and prints out the status code from the server response when a response has been received.
*
*
* keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(purgeDeletedKeyResponse ->
* System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode()));
*
*
*
* @param name The name of the {@link KeyVaultKey deleted key}.
*
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> purgeDeletedKeyWithResponse(String name) {
try {
return implClient.purgeDeletedKeyWithResponseAsync(vaultUrl, name)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapPurgeDeletedKeyException);
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapPurgeDeletedKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* Recovers the {@link KeyVaultKey deleted key} in the key vault to its latest version and can only be performed
* on a soft-delete enabled vault. An attempt to recover an {@link KeyVaultKey non-deleted key} will return an
* error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation
* requires the {@code keys/recover} permission.
*
* Code Samples
* Recovers the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the
* call asynchronously and prints out the recovered key details when a response has been received.
*
*
* keyAsyncClient.beginRecoverDeletedKey("deletedKeyName")
* .subscribe(pollResponse -> {
* System.out.printf("Recovery status: %s%n", pollResponse.getStatus());
* System.out.printf("Key name: %s%n", pollResponse.getValue().getName());
* System.out.printf("Key type: %s%n", pollResponse.getValue().getKeyType());
* });
*
*
*
* @param name The name of the {@link KeyVaultKey deleted key} to be recovered.
*
* @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux beginRecoverDeletedKey(String name) {
return new PollerFlux<>(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name),
(context, firstResponse) -> Mono.empty(), context -> Mono.empty());
}
private Function, Mono> recoverActivationOperation(String name) {
return pollingContext -> implClient.recoverDeletedKeyAsync(vaultUrl, name)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapRecoverDeletedKeyException)
.map(KeyVaultKeysModelsUtils::createKeyVaultKey);
}
static HttpResponseException mapRecoverDeletedKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
private Function, Mono>> recoverPollOperation(
String keyName) {
return pollingContext -> implClient.getKeyAsync(vaultUrl, keyName, null)
.map(keyResponse -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
createKeyVaultKey(keyResponse)))
.onErrorResume(KeyVaultErrorException.class, ex -> {
if (ex.getResponse().getStatusCode() == 404) {
return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue()));
} else {
// This means permission is not granted for the get key operation. In both cases recovery operation
// was successful when activation operation succeeded before reaching here.
return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue()));
}
})
// This means permission is not granted for the get deleted key operation. In both cases deletion
// operation was successful when activation operation succeeded before reaching here.
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue()));
}
/**
* Requests a backup of the specified {@link KeyVaultKey key} be downloaded to the client. The key backup
* operation exports a {@link KeyVaultKey key} from Azure Key Vault in a protected form. Note that this operation
* does not return key material in a form that can be used outside the Azure Key Vault system, the returned key
* material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this
* operation is to allow a client to generate a {@link KeyVaultKey key} in one Azure Key Vault instance, backup the
* {@link KeyVaultKey key}, and then restore it into another Azure Key Vault instance. The backup operation may
* be used to export, in protected form, any {@link KeyType key type} from Azure Key Vault. Individual versions
* of a {@link KeyVaultKey key} cannot be backed up. {@code Backup/Restore} can be performed within geographical
* boundaries only; meaning that a backup from one geographical area cannot be restored to another geographical
* area. For example, a backup from the US geographical area cannot be restored in an EU geographical area. This
* operation requires the {@code key/backup} permission.
*
* Code Samples
* Backs up the {@link KeyVaultKey key} from the key vault. Subscribes to the call asynchronously and prints out
* the length of the key's backup byte array returned in the response.
*
*
* keyAsyncClient.backupKey("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(bytes ->
* System.out.printf("Key backup byte array length: %s%n", bytes.length));
*
*
*
* @param name The name of the {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the backed up key blob.
*
* @throws HttpResponseException When a key with {@code name} is an empty string.
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono backupKey(String name) {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
}
/**
* Requests a backup of the specified {@link KeyVaultKey key} be downloaded to the client. The key backup
* operation exports a {@link KeyVaultKey key} from Azure Key Vault in a protected form. Note that this operation
* does not return key material in a form that can be used outside the Azure Key Vault system, the returned key
* material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this
* operation is to allow a client to generate a {@link KeyVaultKey key} in one Azure Key Vault instance, backup the
* {@link KeyVaultKey key}, and then restore it into another Azure Key Vault instance. The backup operation may
* be used to export, in protected form, any {@link KeyType key type} from Azure Key Vault. Individual versions
* of a {@link KeyVaultKey key} cannot be backed up. {@code Backup/Restore} can be performed within geographical
* boundaries only; meaning that a backup from one geographical area cannot be restored to another geographical
* area. For example, a backup from the US geographical area cannot be restored in an EU geographical area. This
* operation requires the {@code key/backup} permission.
*
* Code Samples
* Backs up the {@link KeyVaultKey key} from the key vault. Subscribes to the call asynchronously and prints out
* the length of the key's backup byte array returned in the response.
*
*
* keyAsyncClient.backupKeyWithResponse("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(backupKeyResponse ->
* System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length));
*
*
*
* @param name The name of the {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the backed up
* key blob.
*
* @throws ResourceNotFoundException When a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException When a key with {@code name} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> backupKeyWithResponse(String name) {
try {
return implClient.backupKeyWithResponseAsync(vaultUrl, name)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapBackupKeyException)
.map(response -> new SimpleResponse<>(response, response.getValue().getValue()));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapBackupKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* Restores a backed up {@link KeyVaultKey key} to a vault. Imports a previously backed up {@link KeyVaultKey key}
* into Azure Key Vault, restoring the {@link KeyVaultKey key}, its key identifier, attributes and access control
* policies. The restore operation may be used to import a previously backed up {@link KeyVaultKey key}. Individual
* versions of a {@link KeyVaultKey key} cannot be restored. The {@link KeyVaultKey key} is restored in its entirety
* with the same key name as it had when it was backed up. If the key name is not available in the target key vault,
* the restore operation will be rejected. While the key name is retained during restore, the final key identifier
* will change if the {@link KeyVaultKey key} is restored to a different vault. Restore will restore all versions
* and preserve version identifiers. The restore operation is subject to security constraints: The target key
* vault must be owned by the same Microsoft Azure Subscription as the source key vault. The user must have
* the {@code restore} permission in the target key vault. This operation requires the {@code keys/restore}
* permission.
*
* Code Samples
* Restores the {@link KeyVaultKey key} in the key vault from its backup. Subscribes to the call asynchronously
* and prints out the restored key details when a response has been received.
* //Pass the Key Backup Byte array to the restore operation.
*
*
* keyAsyncClient.restoreKeyBackup(keyBackupByteArray)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(restoreKeyResponse ->
* System.out.printf("Restored key with name: %s and: id %s%n", restoreKeyResponse.getName(),
* restoreKeyResponse.getId()));
*
*
*
* @param backup The backup blob associated with the {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
*
* @throws ResourceModifiedException When {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono restoreKeyBackup(byte[] backup) {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
}
/**
* Restores a backed up {@link KeyVaultKey key} to a vault. Imports a previously backed up {@link KeyVaultKey key}
* into Azure Key Vault, restoring the {@link KeyVaultKey key}, its key identifier, attributes and access control
* policies. The restore operation may be used to import a previously backed up {@link KeyVaultKey key}. Individual
* versions of a {@link KeyVaultKey key} cannot be restored. The {@link KeyVaultKey key} is restored in its entirety
* with the same key name as it had when it was backed up. If the key name is not available in the target key vault,
* the restore operation will be rejected. While the key name is retained during restore, the final key identifier
* will change if the {@link KeyVaultKey key} is restored to a different vault. Restore will restore all versions
* and preserve version identifiers. The restore operation is subject to security constraints: The target key
* vault must be owned by the same Microsoft Azure Subscription as the source key vault. The user must have
* the {@code restore} permission in the target key vault. This operation requires the {@code keys/restore}
* permission.
*
* Code Samples
* Restores the {@link KeyVaultKey key} in the key vault from its backup. Subscribes to the call asynchronously
* and prints out the restored key details when a response has been received.
* //Pass the Key Backup Byte array to the restore operation.
*
*
* keyAsyncClient.restoreKeyBackupWithResponse(keyBackupByteArray)
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(restoreKeyBackupResponse ->
* System.out.printf("Restored key with name: %s and: id %s%n",
* restoreKeyBackupResponse.getValue().getName(), restoreKeyBackupResponse.getValue().getId()));
*
*
*
* @param backup The backup blob associated with the {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the
* {@link KeyVaultKey restored key}.
*
* @throws ResourceModifiedException When {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> restoreKeyBackupWithResponse(byte[] backup) {
try {
return implClient.restoreKeyWithResponseAsync(vaultUrl, backup)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapRestoreKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapRestoreKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 400)
? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* List {@link KeyVaultKey keys} in the key vault. Retrieves a list of the {@link KeyVaultKey keys} in the key
* vault as {@link JsonWebKey} structures that contain the public part of a stored {@link KeyVaultKey key}. The list
* operation is applicable to all {@link KeyType key types} and the individual {@link KeyVaultKey key} response
* in the list is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* Code Samples
* It is possible to get {@link KeyVaultKey full keys} with key material from this information. Convert the
* {@link Flux} containing {@link KeyProperties key properties} to {@link Flux} containing
* {@link KeyVaultKey key} using {@link KeyAsyncClient#getKey(String, String)} within
* {@link Flux#flatMap(Function)}.
*
*
* keyAsyncClient.listPropertiesOfKeys()
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion()))
* .subscribe(key -> System.out.printf("Retrieved key with name: %s and type: %s%n",
* key.getName(),
* key.getKeyType()));
*
*
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux listPropertiesOfKeys() {
return new PagedFlux<>(maxResults -> implClient.getKeysSinglePageAsync(vaultUrl, maxResults)
.map(KeyAsyncClient::mapKeyItemPagedResponse),
(continuationToken, maxResults) -> implClient.getKeysNextSinglePageAsync(continuationToken, vaultUrl)
.map(KeyAsyncClient::mapKeyItemPagedResponse));
}
static PagedResponse mapKeyItemPagedResponse(PagedResponse page) {
List properties = new ArrayList<>(page.getValue().size());
for (KeyItem keyItem : page.getValue()) {
properties.add(KeyVaultKeysModelsUtils.createKeyProperties(keyItem));
}
return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), properties,
page.getContinuationToken(), null);
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The {@link DeletedKey deleted keys} are retrieved as
* {@link JsonWebKey} structures that contain the public part of a {@link DeletedKey deleted key}. The get deleted
* keys operation is applicable for vaults enabled for soft-delete. This operation requires the {@code keys/list}
* permission.
*
* Code Samples
* Lists the {@link DeletedKey deleted keys} in the key vault. Subscribes to the call asynchronously and prints
* out the recovery id of each {@link DeletedKey deleted key} when a response has been received.
*
*
* keyAsyncClient.listDeletedKeys()
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .subscribe(deletedKey ->
* System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()));
*
*
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux listDeletedKeys() {
return new PagedFlux<>(maxResults -> implClient.getDeletedKeysSinglePageAsync(vaultUrl, maxResults)
.map(KeyAsyncClient::mapDeletedKeyItemPagedResponse),
(continuationToken, maxResults) -> implClient.getDeletedKeysNextSinglePageAsync(continuationToken, vaultUrl)
.map(KeyAsyncClient::mapDeletedKeyItemPagedResponse));
}
static PagedResponse mapDeletedKeyItemPagedResponse(PagedResponse page) {
List properties = new ArrayList<>(page.getValue().size());
for (DeletedKeyItem keyItem : page.getValue()) {
properties.add(KeyVaultKeysModelsUtils.createDeletedKey(keyItem));
}
return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), properties,
page.getContinuationToken(), null);
}
/**
* List all versions of the specified {@link KeyVaultKey keys}. The individual key response in the flux is
* represented by {@link KeyProperties} as only the key identifier, attributes and tags are provided in the
* response. The key material values are not provided in the response. This operation requires the
* {@code keys/list} permission.
*
* Code Samples
* It is possible to get the keys with key material of all the versions from this information. Convert the
* {@link Flux} containing {@link KeyProperties key properties} to {@link Flux} containing
* {@link KeyVaultKey key } using {@link KeyAsyncClient#getKey(String, String)} within
* {@link Flux#flatMap(Function)}.
*
*
* keyAsyncClient.listPropertiesOfKeyVersions("keyName")
* .contextWrite(Context.of("key1", "value1", "key2", "value2"))
* .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion()))
* .subscribe(key ->
* System.out.printf("Retrieved key version: %s with name: %s and type: %s%n",
* key.getProperties().getVersion(), key.getName(), key.getKeyType()));
*
*
*
* @param name The name of the {@link KeyVaultKey key}.
*
* @return A {@link PagedFlux} containing {@link KeyProperties} of all the versions of the specified
* {@link KeyVaultKey keys} in the vault. {@link Flux} is empty if key with {@code name} does not exist in the key
* vault.
*
* @throws ResourceNotFoundException When a given key {@code name} is {@code null} or an empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux listPropertiesOfKeyVersions(String name) {
return new PagedFlux<>(maxResults -> implClient.getKeyVersionsSinglePageAsync(vaultUrl, name, maxResults)
.map(KeyAsyncClient::mapKeyItemPagedResponse),
(continuationToken, maxResults) -> implClient.getKeyVersionsNextSinglePageAsync(continuationToken, vaultUrl)
.map(KeyAsyncClient::mapKeyItemPagedResponse));
}
/**
* Get the requested number of bytes containing random values from a managed HSM.
*
* Code Samples
* Gets a number of bytes containing random values from a Managed HSM. Prints out the retrieved bytes in
* base64Url format.
*
*
* int amount = 16;
* keyAsyncClient.getRandomBytes(amount)
* .subscribe(randomBytes ->
* System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes)));
*
*
*
* @param count The requested number of random bytes.
*
* @return A {@link Mono} containing the requested number of bytes containing random values from a managed HSM.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono getRandomBytes(int count) {
return getRandomBytesWithResponse(count).flatMap(FluxUtil::toMono);
}
/**
* Get the requested number of bytes containing random values from a managed HSM.
*
* Code Samples
* Gets a number of bytes containing random values from a Managed HSM. Prints out the
* {@link Response HTTP Response} details and the retrieved bytes in base64Url format.
*
*
* int amountOfBytes = 16;
* keyAsyncClient.getRandomBytesWithResponse(amountOfBytes).subscribe(response ->
* System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n",
* response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue())));
*
*
*
* @param count The requested number of random bytes.
*
* @return A {@link Mono} containing the {@link Response HTTP response} for this operation and the requested number
* of bytes containing random values from a managed HSM.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> getRandomBytesWithResponse(int count) {
try {
return withContext(context -> implClient.getRandomBytesWithResponseAsync(vaultUrl, count))
.map(response -> new SimpleResponse<>(response, response.getValue().getValue()));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
/**
* Releases the latest version of a {@link KeyVaultKey key}.
*
* The {@link KeyVaultKey key} must be exportable. This operation requires the {@code keys/release} permission.
*
*
* Code Samples
* Releases a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the signed object
* that contains the {@link KeyVaultKey released key} when a response has been received.
*
*
* String targetAttestationToken = "someAttestationToken";
* ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", targetAttestationToken);
*
* System.out.printf("Signed object containing released key: %s%n", releaseKeyResult);
*
*
*
* @param name The name of the {@link KeyVaultKey key} to release.
* @param targetAttestationToken The attestation assertion for the target of the {@link KeyVaultKey key} release.
*
* @return A {@link Mono} containing the {@link ReleaseKeyResult} containing the released key.
*
* @throws IllegalArgumentException If {@code name} or {@code targetAttestationToken} are {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono releaseKey(String name, String targetAttestationToken) {
return releaseKeyWithResponse(name, null, targetAttestationToken, new ReleaseKeyOptions())
.flatMap(FluxUtil::toMono);
}
/**
* Releases a key.
*
* The key must be exportable. This operation requires the 'keys/release' permission.
*
* Code Samples
* Releases a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the signed object
* that contains the {@link KeyVaultKey released key} when a response has been received.
*
*
* String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
* String myTargetAttestationToken = "someAttestationToken";
*
* keyAsyncClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken)
* .subscribe(releaseKeyResult ->
* System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue()));
*
*
*
* @param name The name of the {@link KeyVaultKey key} to release.
* @param version The version of the key to retrieve. If this is empty or {@code null}, this call is equivalent to
* calling {@link KeyAsyncClient#releaseKey(String, String)}, with the latest key version being released.
* @param targetAttestationToken The attestation assertion for the target of the key release.
*
* @return A {@link Mono} containing the {@link ReleaseKeyResult} containing the released key.
*
* @throws IllegalArgumentException If {@code name} or {@code targetAttestationToken} are {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono releaseKey(String name, String version, String targetAttestationToken) {
return releaseKeyWithResponse(name, version, targetAttestationToken, new ReleaseKeyOptions())
.flatMap(FluxUtil::toMono);
}
/**
* Releases a key.
*
* The key must be exportable. This operation requires the 'keys/release' permission.
*
* Code Samples
* Releases a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the
* {@link Response HTTP Response} details and the signed object that contains the {@link KeyVaultKey released key}
* when a response has been received.
*
*
* String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
* String someTargetAttestationToken = "someAttestationToken";
* ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions()
* .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256)
* .setNonce("someNonce");
*
* keyAsyncClient.releaseKeyWithResponse("keyName", releaseKeyVersion, someTargetAttestationToken,
* releaseKeyOptions)
* .subscribe(releaseKeyResponse ->
* System.out.printf("Response received successfully with status code: %d. Signed object containing"
* + "released key: %s%n", releaseKeyResponse.getStatusCode(),
* releaseKeyResponse.getValue().getValue()));
*
*
*
* @param name The name of the key to release.
* @param version The version of the key to retrieve. If this is empty or {@code null}, this call is equivalent to
* calling {@link KeyAsyncClient#releaseKey(String, String)}, with the latest key version being released.
* @param targetAttestationToken The attestation assertion for the target of the key release.
* @param releaseKeyOptions Additional {@link ReleaseKeyOptions options} for releasing a {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the {@link Response HTTP response} for this operation and the
* {@link ReleaseKeyResult} containing the released key.
*
* @throws IllegalArgumentException If {@code name} or {@code targetAttestationToken} are {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> releaseKeyWithResponse(String name, String version,
String targetAttestationToken,
ReleaseKeyOptions releaseKeyOptions) {
try {
if (CoreUtils.isNullOrEmpty(name) || CoreUtils.isNullOrEmpty(targetAttestationToken)) {
return monoError(LOGGER, new IllegalArgumentException(
"'name' or 'targetAttestationToken' cannot be null or empty."));
}
String nonce = releaseKeyOptions == null ? null : releaseKeyOptions.getNonce();
KeyExportEncryptionAlgorithm algorithm = releaseKeyOptions == null
? null : releaseKeyOptions.getAlgorithm();
return implClient.releaseWithResponseAsync(vaultUrl, name, version, targetAttestationToken, nonce,
algorithm)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapReleaseKeyException);
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapReleaseKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* Rotates a {@link KeyVaultKey key}. The rotate key operation will do so based on
* {@link KeyRotationPolicy key's rotation policy}. This operation requires the {@code keys/rotate} permission.
*
* Code Samples
* Rotates a {@link KeyVaultKey key}. Prints out {@link KeyVaultKey rotated key} details.
*
*
* keyAsyncClient.rotateKey("keyName")
* .subscribe(key ->
* System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(),
* key.getProperties().getVersion()));
*
*
*
* @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the
* specified {@link KeyVaultKey key}.
*
* @return The new version of the rotated {@link KeyVaultKey key}.
*
* @throws IllegalArgumentException If {@code name} is {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono rotateKey(String name) {
return rotateKeyWithResponse(name).flatMap(FluxUtil::toMono);
}
/**
* Rotates a {@link KeyVaultKey key}. The rotate key operation will do so based on
* {@link KeyRotationPolicy key's rotation policy}. This operation requires the {@code keys/rotate} permission.
*
* Code Samples
* Rotates a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the
* {@link Response HTTP Response} and {@link KeyVaultKey rotated key} details when a response has been received.
*
*
* keyAsyncClient.rotateKeyWithResponse("keyName")
* .subscribe(rotateKeyResponse ->
* System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and"
* + "version: %s%n", rotateKeyResponse.getStatusCode(), rotateKeyResponse.getValue().getName(),
* rotateKeyResponse.getValue().getProperties().getVersion()));
*
*
*
* @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the
* specified {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the {@link Response HTTP response} for this operation and the new version of
* the rotated {@link KeyVaultKey key}.
*
* @throws IllegalArgumentException If {@code name} is {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> rotateKeyWithResponse(String name) {
try {
return implClient.rotateKeyWithResponseAsync(vaultUrl, name)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapRotateKeyException)
.map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapRotateKeyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* Gets the {@link KeyRotationPolicy} for the {@link KeyVaultKey key} with the provided name. This operation
* requires the {@code keys/get} permission.
*
* Code Samples
* Retrieves the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the
* call asynchronously and prints out the {@link KeyRotationPolicy rotation policy key} details when a response
* has been received.
*
*
* keyAsyncClient.getKeyRotationPolicy("keyName")
* .subscribe(keyRotationPolicy ->
* System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId()));
*
*
*
* @param keyName The name of the {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the {@link KeyRotationPolicy} for the key.
*
* @throws IllegalArgumentException If {@code name} is {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono getKeyRotationPolicy(String keyName) {
return getKeyRotationPolicyWithResponse(keyName).flatMap(FluxUtil::toMono);
}
/**
* Gets the {@link KeyRotationPolicy} for the {@link KeyVaultKey key} with the provided name. This operation
* requires the {@code keys/get} permission.
*
* Code Samples
* Retrieves the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the
* call asynchronously and prints out the {@link Response HTTP Response} and
* {@link KeyRotationPolicy rotation policy key} details when a response has been received.
*
*
* keyAsyncClient.getKeyRotationPolicyWithResponse("keyName")
* .subscribe(getKeyRotationPolicyResponse ->
* System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy"
* + "with id: %s%n", getKeyRotationPolicyResponse.getStatusCode(),
* getKeyRotationPolicyResponse.getValue().getId()));
*
*
*
* @param keyName The name of the {@link KeyVaultKey key}.
*
* @return A {@link Mono} containing the {@link Response HTTP response} for this operation and the
* {@link KeyRotationPolicy} for the key.
*
* @throws IllegalArgumentException If {@code name} is {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> getKeyRotationPolicyWithResponse(String keyName) {
try {
return implClient.getKeyRotationPolicyWithResponseAsync(vaultUrl, keyName)
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapGetKeyRotationPolicyException)
.map(response -> new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapGetKeyRotationPolicyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
/**
* Updates the {@link KeyRotationPolicy} of the key with the provided name. This operation requires the
* {@code keys/update} permission.
*
* Code Samples
* Updates the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the
* call asynchronously and prints out the {@link KeyRotationPolicy rotation policy key} details when a response
* has been received.
*
*
* List<KeyRotationLifetimeAction> lifetimeActions = new ArrayList<>();
* KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
* .setTimeAfterCreate("P90D");
* KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY)
* .setTimeBeforeExpiry("P45D");
*
* lifetimeActions.add(rotateLifetimeAction);
* lifetimeActions.add(notifyLifetimeAction);
*
* KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy()
* .setLifetimeActions(lifetimeActions)
* .setExpiresIn("P6M");
*
* keyAsyncClient.updateKeyRotationPolicy("keyName", keyRotationPolicy)
* .subscribe(updatedPolicy ->
* System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId()));
*
*
*
* @param keyName The name of the {@link KeyVaultKey key}.
* @param keyRotationPolicy The {@link KeyRotationPolicy} for the key.
*
* @return A {@link Mono} containing the {@link KeyRotationPolicy} for the key.
*
* @throws IllegalArgumentException If {@code name} is {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono updateKeyRotationPolicy(String keyName, KeyRotationPolicy keyRotationPolicy) {
return updateKeyRotationPolicyWithResponse(keyName, keyRotationPolicy).flatMap(FluxUtil::toMono);
}
/**
* Updates the {@link KeyRotationPolicy} of the key with the provided name. This operation requires the
* {@code keys/update} permission.
*
* Code Samples
* Updates the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the
* call asynchronously and prints out the {@link Response HTTP Response} and
* {@link KeyRotationPolicy rotation policy key} details when a response has been received.
*
*
* List<KeyRotationLifetimeAction> myLifetimeActions = new ArrayList<>();
* KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
* .setTimeAfterCreate("P90D");
* KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY)
* .setTimeBeforeExpiry("P45D");
*
* myLifetimeActions.add(myRotateLifetimeAction);
* myLifetimeActions.add(myNotifyLifetimeAction);
*
* KeyRotationPolicy myKeyRotationPolicy = new KeyRotationPolicy()
* .setLifetimeActions(myLifetimeActions)
* .setExpiresIn("P6M");
*
* keyAsyncClient.updateKeyRotationPolicyWithResponse("keyName", myKeyRotationPolicy)
* .subscribe(myUpdatedPolicyResponse ->
* System.out.printf("Response received successfully with status code: %d. Updated key rotation policy"
* + "with id: %s%n", myUpdatedPolicyResponse.getStatusCode(),
* myUpdatedPolicyResponse.getValue().getId()));
*
*
*
* @param keyName The name of the {@link KeyVaultKey key}.
* @param keyRotationPolicy The {@link KeyRotationPolicy} for the key.
*
* @return A {@link Mono} containing the {@link Response HTTP response} for this operation and the
* {@link KeyRotationPolicy} for the key.
*
* @throws IllegalArgumentException If {@code name} is {@code null} or empty.
* @throws ResourceNotFoundException If the {@link KeyVaultKey key} for the provided {@code name} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono> updateKeyRotationPolicyWithResponse(String keyName,
KeyRotationPolicy keyRotationPolicy) {
try {
return implClient.updateKeyRotationPolicyWithResponseAsync(vaultUrl, keyName,
mapKeyRotationPolicy(keyRotationPolicy))
.onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapUpdateKeyRotationPolicyException)
.map(response -> new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue())));
} catch (RuntimeException e) {
return monoError(LOGGER, e);
}
}
static HttpResponseException mapUpdateKeyRotationPolicyException(KeyVaultErrorException ex) {
return (ex.getResponse().getStatusCode() == 404)
? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue())
: ex;
}
}