Class KeyClient
KeyClient provides synchronous methods to manage keys in the Azure Key Vault. The
client supports creating, retrieving, updating, deleting, purging, backing up, restoring, listing, releasing and
rotating the keys. The client also supports listing deleted keys for a
soft-delete enabled Azure Key Vault.
Getting Started
In order to interact with the Azure Key Vault service, you will need to create an instance of the
KeyClient 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 Synchronous Key Client
The following code sample demonstrates the creation of a KeyClient, using the KeyClientBuilder
to configure it.
KeyClient keyClient = new KeyClientBuilder()
.vaultUrl("<your-key-vault-url>")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
Create a Cryptographic Key
TheKeyClient can be used to create a key in the key vault.
Code Sample:
The following code sample demonstrates how to synchronously create a cryptographic key in the key vault,
using the createKey(String, KeyType) API.
KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC);
System.out.printf("Created key with name: %s and id: %s%n", key.getName(), key.getId());
Note: For the asynchronous sample, refer to KeyAsyncClient.
Get a Cryptographic Key
TheKeyClient can be used to retrieve a key from the key vault.
Code Sample:
The following code sample demonstrates how to synchronously retrieve a key from the key vault, using
the getKey(String) API.
KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName");
System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(),
keyWithVersionValue.getId());
Note: For the asynchronous sample, refer to KeyAsyncClient.
Delete a Cryptographic Key
TheKeyClient can be used to delete a key from the key vault.
Code Sample:
The following code sample demonstrates how to synchronously delete a key from the
key vault, using the beginDeleteKey(String) API.
SyncPoller<DeletedKey, Void> deleteKeyPoller = keyClient.beginDeleteKey("keyName");
PollResponse<DeletedKey> deleteKeyPollResponse = deleteKeyPoller.poll();
// Deleted date only works for SoftDelete Enabled Key Vault.
DeletedKey deletedKey = deleteKeyPollResponse.getValue();
System.out.printf("Key delete date: %s%n", deletedKey.getDeletedOn());
System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId());
// Key is being deleted on the server.
deleteKeyPoller.waitForCompletion();
// Key is deleted
Note: For the asynchronous sample, refer to KeyAsyncClient.
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionbyte[]Requests a backup of the specifiedkeybe downloaded to the client.com.azure.core.http.rest.Response<byte[]> backupKeyWithResponse(String name, com.azure.core.util.Context context) Requests a backup of the specifiedkeybe downloaded to the client.com.azure.core.util.polling.SyncPoller<DeletedKey, Void> beginDeleteKey(String name) Deletes akeyof any type from the key vault.com.azure.core.util.polling.SyncPoller<KeyVaultKey, Void> beginRecoverDeletedKey(String name) Recovers thedeleted keyin the key vault to its latest version and can only be performed on a soft-delete enabled vault.createEcKey(CreateEcKeyOptions createEcKeyOptions) Creates a newEC keyand stores it in the key vault.com.azure.core.http.rest.Response<KeyVaultKey> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, com.azure.core.util.Context context) Creates a newEC keyand stores it in the key vault.createKey(CreateKeyOptions createKeyOptions) Creates a newkeyand stores it in the key vault.Creates a newkeyand stores it in the key vault.com.azure.core.http.rest.Response<KeyVaultKey> createKeyWithResponse(CreateKeyOptions createKeyOptions, com.azure.core.util.Context context) Creates a newkeyand stores it in the key vault.createOctKey(CreateOctKeyOptions createOctKeyOptions) Creates and stores a newsymmetric keyin the key vault.com.azure.core.http.rest.Response<KeyVaultKey> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions, com.azure.core.util.Context context) Creates and stores a newsymmetric keyin the key vault.createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) Creates a newRSA keyand stores it in the key vault.com.azure.core.http.rest.Response<KeyVaultKey> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, com.azure.core.util.Context context) Creates a newRSA keyand stores it in the key vault.getCryptographyClient(String keyName) Creates aCryptographyClientfor the latest version of a given key.getCryptographyClient(String keyName, String keyVersion) Creates aCryptographyClientfor a given key version.getDeletedKey(String name) Gets the public part of adeleted key.com.azure.core.http.rest.Response<DeletedKey> getDeletedKeyWithResponse(String name, com.azure.core.util.Context context) Gets the public part of adeleted key.Gets the public part of the specifiedkeyand key version.Gets the public part of the specifiedkeyand key version.getKeyAttestation(String name) Gets the public part of the latest version of the specifiedkey, including its key attestation information.com.azure.core.http.rest.Response<KeyVaultKey> getKeyAttestationWithResponse(String name, String version, com.azure.core.util.Context context) Gets the public part of the specifiedkeyand key version, including its key attestation information.getKeyRotationPolicy(String keyName) Gets theKeyRotationPolicyfor thekeywith the provided name.com.azure.core.http.rest.Response<KeyRotationPolicy> getKeyRotationPolicyWithResponse(String keyName, com.azure.core.util.Context context) Gets theKeyRotationPolicyfor thekeywith the provided name.com.azure.core.http.rest.Response<KeyVaultKey> getKeyWithResponse(String name, String version, com.azure.core.util.Context context) Gets the public part of the specifiedkeyand key version.byte[]getRandomBytes(int count) Get the requested number of bytes containing random values from a managed HSM.com.azure.core.http.rest.Response<byte[]> getRandomBytesWithResponse(int count, com.azure.core.util.Context context) Get the requested number of bytes containing random values from a managed HSM.Get the vault endpoint url to which service requests are sent to.importKey(ImportKeyOptions importKeyOptions) Imports an externally createdkeyand stores it in the key vault.importKey(String name, JsonWebKey keyMaterial) Imports an externally createdkeyand stores it in the key vault.com.azure.core.http.rest.Response<KeyVaultKey> importKeyWithResponse(ImportKeyOptions importKeyOptions, com.azure.core.util.Context context) Imports an externally createdkeyand stores it in the key vault.com.azure.core.http.rest.PagedIterable<DeletedKey> Listsdeleted keysof the key vault.com.azure.core.http.rest.PagedIterable<DeletedKey> listDeletedKeys(com.azure.core.util.Context context) Listsdeleted keysof the key vault.com.azure.core.http.rest.PagedIterable<KeyProperties> Listkeysin the key vault.com.azure.core.http.rest.PagedIterable<KeyProperties> listPropertiesOfKeys(com.azure.core.util.Context context) Listkeysin the key vault.com.azure.core.http.rest.PagedIterable<KeyProperties> List all versions of the specifiedkeys.com.azure.core.http.rest.PagedIterable<KeyProperties> listPropertiesOfKeyVersions(String name, com.azure.core.util.Context context) List all versions of the specifiedkeys.voidpurgeDeletedKey(String name) Permanently deletes the specifiedkeywithout the possibility of recovery.com.azure.core.http.rest.Response<Void> purgeDeletedKeyWithResponse(String name, com.azure.core.util.Context context) Permanently deletes the specifiedkeywithout the possibility of recovery.releaseKey(String name, String targetAttestationToken) Releases the latest version of akey.releaseKey(String name, String version, String targetAttestationToken) Releases a specific version of akey.com.azure.core.http.rest.Response<ReleaseKeyResult> releaseKeyWithResponse(String name, String version, String targetAttestationToken, ReleaseKeyOptions releaseKeyOptions, com.azure.core.util.Context context) Releases akey.restoreKeyBackup(byte[] backup) Restores a backed upkeyto a vault.com.azure.core.http.rest.Response<KeyVaultKey> restoreKeyBackupWithResponse(byte[] backup, com.azure.core.util.Context context) Restores a backed upkeyto a vault.Rotates akey.com.azure.core.http.rest.Response<KeyVaultKey> rotateKeyWithResponse(String name, com.azure.core.util.Context context) Rotates akey.updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) Updates theattributesandkey operationsassociated with the specifiedkey, but not the cryptographic key material of the specifiedkeyin the key vault.com.azure.core.http.rest.Response<KeyVaultKey> updateKeyPropertiesWithResponse(KeyProperties keyProperties, com.azure.core.util.Context context, KeyOperation... keyOperations) Updates theattributesandkey operationsassociated with the specifiedkey, but not the cryptographic key material of the specifiedkeyin the key vault.updateKeyRotationPolicy(String keyName, KeyRotationPolicy keyRotationPolicy) Updates theKeyRotationPolicyof thekeywith the provided name.com.azure.core.http.rest.Response<KeyRotationPolicy> updateKeyRotationPolicyWithResponse(String keyName, KeyRotationPolicy keyRotationPolicy, com.azure.core.util.Context context) Updates theKeyRotationPolicyof the key with the provided name.
-
Method Details
-
getVaultUrl
Get the vault endpoint url to which service requests are sent to.- Returns:
- The vault endpoint url.
-
getCryptographyClient
Creates aCryptographyClientfor the latest version of a given key.To ensure correct behavior when performing operations such as
Decrypt,UnwrapandVerify, it is recommended to use aCryptographyClientcreated for the specific key version that was used for the corresponding inverse operation:Encrypt,Wrap, orSign, respectively.You can provide a key version either via
getCryptographyClient(String, String)or by ensuring it is included in thekeyIdentifierpassed toCryptographyClientBuilder.keyIdentifier(String)before building a client.- Parameters:
keyName- The name of the key.- Returns:
- An instance of
CryptographyClientassociated with the latest version of a key with the provided name. - Throws:
IllegalArgumentException- IfkeyNameisnullor empty.
-
getCryptographyClient
Creates aCryptographyClientfor a given key version.- Parameters:
keyName- The name of the key.keyVersion- The key version.- Returns:
- An instance of
CryptographyClientassociated with a key with the provided name and version. IfkeyVersionisnullor empty, the client will use the latest version of the key. - Throws:
IllegalArgumentException- IfkeyNameisnullor empty.
-
createKey
Creates a newkeyand stores it in the key vault. The create key operation can be used to create anykeyTypein Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
keyTypeindicates the type ofkeyto create. Possible values include:EC,EC-HSM,RSA,RSA-HSM,OCT, andOCT-HSM.Code Samples
Creates a new
EC key. Prints out the details of thecreated key.KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC); System.out.printf("Created key with name: %s and id: %s%n", key.getName(), key.getId());- Parameters:
name- The name of thekeybeing created.keyType- The type ofkeyto create. For valid values, seeKeyType.- Returns:
- The
created key. - Throws:
com.azure.core.exception.ResourceModifiedException- IfnameorkeyTypearenull.com.azure.core.exception.HttpResponseException- Ifnameis an empty string.
-
createKey
Creates a newkeyand stores it in the key vault. The create key operation can be used to create anykeyTypein Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
CreateKeyOptionsparameter is required. TheexpiresandnotBeforevalues are optional. TheCreateKeyOptions.isEnabled()enabled} field is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofkeyto create. Possible values include:EC,EC-HSM,RSA,RSA-HSM,OCT, andOCT-HSM.Code Samples
Creates a new
RSA keywhich activates in one day and expires in one year. Prints out the details of thecreated key.CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); KeyVaultKey optionsKey = keyClient.createKey(createKeyOptions); System.out.printf("Created key with name: %s and id: %s%n", optionsKey.getName(), optionsKey.getId());- Parameters:
createKeyOptions- Theoptions objectcontaining information about thekeybeing created.- Returns:
- The
created key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateKeyOptionsisnull.com.azure.core.exception.HttpResponseException- Ifnameis an empty string.
-
createKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> createKeyWithResponse(CreateKeyOptions createKeyOptions, com.azure.core.util.Context context) Creates a newkeyand stores it in the key vault. The create key operation can be used to create anykeyTypein Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
CreateKeyOptionsparameter is required. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofkeyto create. Possible values include:EC,EC-HSM,RSA,RSA-HSM,OCT, andOCT-HSM.Code Samples
Creates a new
RSA keywhich activates in one day and expires in one year. Prints out the details of thecreated key.CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); Response<KeyVaultKey> createKeyResponse = keyClient.createKeyWithResponse(createKeyOptions, new Context("key1", "value1")); System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(), createKeyResponse.getValue().getId());- Parameters:
createKeyOptions- Theoptions objectcontaining information about thekeybeing created.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains thecreated key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateKeyOptionsis malformed.
-
createRsaKey
Creates a newRSA keyand 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 akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
CreateRsaKeyOptionsparameter is required. ThekeySizecan be optionally specified. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofkeyto create. Possible values include:RSAandRSA-HSM.Code Samples
Creates a new
RSA keywith size 2048 which activates in one day and expires in one year. Prints out the details of thecreated key.CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") .setKeySize(2048) .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); KeyVaultKey rsaKey = keyClient.createRsaKey(createRsaKeyOptions); System.out.printf("Created key with name: %s and id: %s%n", rsaKey.getName(), rsaKey.getId());- Parameters:
createRsaKeyOptions- Theoptions objectcontaining information about theRSA keybeing created.- Returns:
- The
created key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateRsaKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateRsaKeyOptionsis malformed.
-
createRsaKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, com.azure.core.util.Context context) Creates a newRSA keyand 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 akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
CreateRsaKeyOptionsparameter is required. ThekeySizecan be optionally specified. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofkeyto create. Possible values include:RSAandRSA-HSM.Code Samples
Creates a new
RSA keywith size 2048 which activates in one day and expires in one year. Prints out the details of thecreated key.CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") .setKeySize(2048) .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); Response<KeyVaultKey> createRsaKeyResponse = keyClient.createRsaKeyWithResponse(createRsaKeyOptions, new Context("key1", "value1")); System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(), createRsaKeyResponse.getValue().getId());- Parameters:
createRsaKeyOptions- Theoptions objectcontaining information about theRSA keybeing created.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains thecreated key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateRsaKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateRsaKeyOptionsis malformed.
-
createEcKey
Creates a newEC keyand stores it in the key vault. The create EC key operation can be used to create any ECkey typein Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
CreateEcKeyOptionsparameter is required. Thekey curvecan be optionally specified. If not specified, the default valueP-256is used by Azure Key Vault. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofKeyVaultKeykey to create. Possible values include:ECandEC-HSM.Code Samples
Creates a new
EC keywith aP-384web key curve. The key activates in one day and expires in one year. Prints out the details of thecreated key.CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") .setCurveName(KeyCurveName.P_384) .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); KeyVaultKey ecKey = keyClient.createEcKey(createEcKeyOptions); System.out.printf("Created key with name: %s and id: %s%n", ecKey.getName(), ecKey.getId());- Parameters:
createEcKeyOptions- Theoptions objectcontaining information about theEC keybeing created.- Returns:
- The
created key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateEcKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateEcKeyOptionsis malformed.
-
createEcKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, com.azure.core.util.Context context) Creates a newEC keyand stores it in the key vault. The create EC key operation can be used to create any ECkey typein Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. It requires thekeys/createpermission.The
CreateEcKeyOptionsparameter is required. Thekey curvecan be optionally specified. If not specified, the default valueP-256is used by Azure Key Vault. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofKeyVaultKeykey to create. Possible values include:ECandEC-HSM.Code Samples
Creates a new
EC keywith aP-384web key curve. The key activates in one day and expires in one year. Prints out the details of thecreated key.CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") .setCurveName(KeyCurveName.P_384) .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); Response<KeyVaultKey> createEcKeyResponse = keyClient.createEcKeyWithResponse(createEcKeyOptions, new Context("key1", "value1")); System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(), createEcKeyResponse.getValue().getId());- Parameters:
createEcKeyOptions- Theoptions objectcontaining information about theEC keybeing created.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains thecreated key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateEcKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateEcKeyOptionsis malformed.
-
createOctKey
Creates and stores a newsymmetric keyin the key vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of the key. This operation requires thekeys/createpermission.The
CreateOctKeyOptionsparameter is required. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofKeyVaultKeykey to create. Possible values include:OCTandOCT-HSM.Code Samples
Creates a new
symmetric key. Thekeyactivates in one day and expires in one year. Prints out the details of the newlycreated key.CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); KeyVaultKey octKey = keyClient.createOctKey(createOctKeyOptions); System.out.printf("Created key with name: %s and id: %s%n", octKey.getName(), octKey.getId());- Parameters:
createOctKeyOptions- Theoptions objectcontaining information about thesymmetric keybeing created.- Returns:
- The
created key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateOctKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateOctKeyOptionsis malformed.
-
createOctKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions, com.azure.core.util.Context context) Creates and stores a newsymmetric keyin the key vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of the key. This operation requires thekeys/createpermission.The
CreateOctKeyOptionsparameter is required. TheexpiresandnotBeforevalues are optional. Theenabledfield is set totrueby Azure Key Vault, if not specified.The
keyTypeindicates the type ofKeyVaultKeykey to create. Possible values include:OCTandOCT-HSM.Code Samples
Creates a new
symmetric key. Thekeyactivates in one day and expires in one year. Prints out the details of the newlycreated key.CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") .setNotBefore(OffsetDateTime.now().plusDays(1)) .setExpiresOn(OffsetDateTime.now().plusYears(1)); Response<KeyVaultKey> createOctKeyResponse = keyClient.createOctKeyWithResponse(createOctKeyOptions, new Context("key1", "value1")); System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(), createOctKeyResponse.getValue().getId());- Parameters:
createOctKeyOptions- Theoptions objectcontaining information about thesymmetric keybeing created.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains thecreated key. - Throws:
com.azure.core.exception.HttpResponseException- IfCreateKeyOptions.getName()is an empty string.NullPointerException- IfcreateOctKeyOptionsisnull.com.azure.core.exception.ResourceModifiedException- IfcreateOctKeyOptionsis malformed.
-
importKey
Imports an externally createdkeyand stores it in the key vault. The import key operation may be used to import anykey typeinto Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. This operation requires thekeys/importpermission.Code Samples
Imports a new
keyinto the key vault. Prints out the details of theimported key.KeyVaultKey key = keyClient.importKey("keyName", jsonWebKeyToImport); System.out.printf("Imported key with name: %s and id: %s%n", key.getName(), key.getId());- Parameters:
name- The name for theimported key.keyMaterial- TheJsonWebKeybeing imported.- Returns:
- The
imported key. - Throws:
com.azure.core.exception.HttpResponseException- Ifnameis an empty string.
-
importKey
Imports an externally createdkeyand stores it in the key vault. The import key operation may be used to import anykey typeinto Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. This operation requires thekeys/importpermission.ImportKeyOptionsis required and its fieldsnameandkey materialcannot benull. TheexpiresandnotBeforevalues inkeyImportOptionsare optional. If not specified, no values are set for the fields. Theenabledfield is set totrueand thehsmfield is set tofalseby Azure Key Vault, if they are not specified.Code Samples
Imports a new
keyinto the key vault. Prints out the details of theimported key.ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport) .setHardwareProtected(false); KeyVaultKey importedKey = keyClient.importKey(options); System.out.printf("Imported key with name: %s and id: %s%n", importedKey.getName(), importedKey.getId());- Parameters:
importKeyOptions- Theoptions objectcontaining information about theJsonWebKeybeing imported.- Returns:
- The
imported key. - Throws:
com.azure.core.exception.HttpResponseException- IfKeyProperties.getName()is an empty string.NullPointerException- IfimportKeyOptionsisnull.
-
importKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> importKeyWithResponse(ImportKeyOptions importKeyOptions, com.azure.core.util.Context context) Imports an externally createdkeyand stores it in the key vault. The import key operation may be used to import anykey typeinto Azure Key Vault. If akeywith the provided name already exists, Azure Key Vault creates a new version of thekey. This operation requires thekeys/importpermission.ImportKeyOptionsis required and its fieldsnameandkey materialcannot benull. TheexpiresandnotBeforevalues inkeyImportOptionsare optional. If not specified, no values are set for the fields. Theenabledfield is set totrueand thehsmfield is set tofalseby Azure Key Vault, if they are not specified.Code Samples
Imports a new
keyinto the key vault. Prints out the details of theimported key.ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport) .setHardwareProtected(false); Response<KeyVaultKey> response = keyClient.importKeyWithResponse(importKeyOptions, new Context("key1", "value1")); System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(), response.getValue().getId());- Parameters:
importKeyOptions- Theoptions objectcontaining information about theJsonWebKeybeing imported.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains theimported key. - Throws:
com.azure.core.exception.HttpResponseException- IfKeyProperties.getName()is an empty string.NullPointerException- IfkeyImportOptionsisnull.
-
getKey
Gets the public part of the specifiedkeyand key version. The get key operation is applicable to allkey typesand it requires thekeys/getpermission.Code Samples
Gets a specific version of the
keyin the key vault. Prints out the details of theretrieved key.String keyVersion = "<key-version>"; KeyVaultKey keyWithVersion = keyClient.getKey("keyName", keyVersion); System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersion.getName(), keyWithVersion.getId());- Parameters:
name- The name of thekey, cannot benull.version- The version of thekeyto retrieve. If this is an empty string ornull, this call is equivalent to callinggetKey(String), with the latest version being retrieved.- Returns:
- The requested
key. The content of thekeyisnullif bothnameandversionarenullor empty. - Throws:
com.azure.core.exception.HttpResponseException- If a validnameand a non-null/emptyversionis specified.com.azure.core.exception.ResourceNotFoundException- When akeywith the providednamedoesn't exist in the key vault or an empty/nullnameand a non-null/emptyversionis provided.
-
getKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> getKeyWithResponse(String name, String version, com.azure.core.util.Context context) Gets the public part of the specifiedkeyand key version. The get key operation is applicable to allkey typesand it requires thekeys/getpermission.Code Samples
Gets a specific version of the
keyin the key vault. Prints out the details of theretrieved key.String keyVersion = "<key-version>"; Response<KeyVaultKey> getKeyResponse = keyClient.getKeyWithResponse("keyName", keyVersion, new Context("key1", "value1")); System.out.printf("Retrieved key with name: %s and: id %s%n", getKeyResponse.getValue().getName(), getKeyResponse.getValue().getId());- Parameters:
name- The name of thekey, cannot benull.version- The version of thekeyto retrieve. If this is an empty string ornull, this call is equivalent to callinggetKey(String), with the latest version being retrieved.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains the requestedkey. The content of thekeyisnullif bothnameandversionarenullor empty. - Throws:
com.azure.core.exception.HttpResponseException- If a validnameand a non-null/emptyversionis specified.com.azure.core.exception.ResourceNotFoundException- When akeywith the providednamedoesn't exist in the key vault or an empty/nullnameand a non-null/emptyversionis provided.
-
getKey
Gets the public part of the specifiedkeyand key version. The get key operation is applicable to allkey typesand it requires thekeys/getpermission.Code Samples
Gets a specific version of the
keyin the key vault. Prints out the details of theretrieved key.KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName"); System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(), keyWithVersionValue.getId());- Parameters:
name- The name of thekey, cannot benull.- Returns:
- The requested
key. The content of the key isnullifnameisnullor empty. - Throws:
com.azure.core.exception.HttpResponseException- If a non null/empty and an invalidnameis specified.com.azure.core.exception.ResourceNotFoundException- When a key with non null/emptynamedoesn't exist in the key vault.
-
updateKeyProperties
Updates theattributesandkey operationsassociated with the specifiedkey, but not the cryptographic key material of the specifiedkeyin the key vault. The update operation changes specifiedattributesof an existing storedkeyandattributesthat are not specified in the request are left unchanged. The cryptographic key material of akeyitself cannot be changed. This operation requires thekeys/setpermission.Code Samples
Gets the latest version of the
key, changes its expiry time andkey operationsand the updates thekeyin the key vault.KeyVaultKey key = keyClient.getKey("keyName"); key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT, KeyOperation.DECRYPT); System.out.printf("Key is updated with name %s and id %s %n", updatedKey.getName(), updatedKey.getId());- Parameters:
keyProperties- Thekey propertiesobject with updated properties.keyOperations- The updatedkey operationsto associate with the key.- Returns:
- A
Responsewhosevaluecontains theupdated key. - Throws:
com.azure.core.exception.HttpResponseException- Ifnameorversionis an empty string.NullPointerException- Ifkeyisnull.com.azure.core.exception.ResourceNotFoundException- When a key withnameandversiondoesn't exist in the key vault.
-
updateKeyPropertiesWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> updateKeyPropertiesWithResponse(KeyProperties keyProperties, com.azure.core.util.Context context, KeyOperation... keyOperations) Updates theattributesandkey operationsassociated with the specifiedkey, but not the cryptographic key material of the specifiedkeyin the key vault. The update operation changes specifiedattributesof an existing storedkeyandattributesthat are not specified in the request are left unchanged. The cryptographic key material of akeyitself cannot be changed. This operation requires thekeys/setpermission.Code Samples
Gets the latest version of the
key, changes its expiry time andkey operationsand the updates thekeyin the key vault.KeyVaultKey key = keyClient.getKey("keyName"); key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); Response<KeyVaultKey> updateKeyResponse = keyClient.updateKeyPropertiesWithResponse(key.getProperties(), new Context("key1", "value1"), KeyOperation.ENCRYPT, KeyOperation.DECRYPT); System.out.printf("Updated key with name: %s and id: %s%n", updateKeyResponse.getValue().getName(), updateKeyResponse.getValue().getId());- Parameters:
keyProperties- Thekey propertiesobject with updated properties.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.keyOperations- The updatedkey operationsto associate with the key.- Returns:
- A
Responsewhosevaluecontains theupdated key. - Throws:
com.azure.core.exception.HttpResponseException- Ifnameorversionis an empty string.NullPointerException- IfkeyPropertiesis null.com.azure.core.exception.ResourceNotFoundException- When a key withnameandversiondoesn't exist in the key vault.
-
beginDeleteKey
Deletes akeyof any type from the key vault. If soft-delete is enabled on the key vault then thekeyis placed in the deleted state and requires to be purged for permanent deletion else thekeyis permanently deleted. The delete operation applies to anykeystored in Azure Key Vault but it cannot be applied to an individual version of akey. This operation removes the cryptographic material associated with thekey, which means thekeyis not usable forSign/Verify,Wrap/UnwraporEncrypt/Decryptoperations. This operation requires thekeys/deletepermission.Code Samples
Deletes the
keyfrom the key vault. Prints out the recovery id of thedeleted key.SyncPoller<DeletedKey, Void> deleteKeyPoller = keyClient.beginDeleteKey("keyName"); PollResponse<DeletedKey> deleteKeyPollResponse = deleteKeyPoller.poll(); // Deleted date only works for SoftDelete Enabled Key Vault. DeletedKey deletedKey = deleteKeyPollResponse.getValue(); System.out.printf("Key delete date: %s%n", deletedKey.getDeletedOn()); System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId()); // Key is being deleted on the server. deleteKeyPoller.waitForCompletion(); // Key is deleted- Parameters:
name- The name of thekeyto be deleted.- Returns:
- A
SyncPollerto poll on and retrievedeleted key - Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
getDeletedKey
Gets the public part of adeleted key. The get deleted Key operation is applicable for soft-delete enabled vaults. This operation requires thekeys/getpermission.Code Samples
Gets the
deleted keyfrom the key vault enabled for soft-delete. Prints out the details of thedeleted key.DeletedKey deletedKey = keyClient.getDeletedKey("keyName"); System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId());- Parameters:
name- The name of the deletedkey.- Returns:
- The
deleted key. - Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
getDeletedKeyWithResponse
public com.azure.core.http.rest.Response<DeletedKey> getDeletedKeyWithResponse(String name, com.azure.core.util.Context context) Gets the public part of adeleted key. The get deleted Key operation is applicable for soft-delete enabled vaults. This operation requires thekeys/getpermission.Code Samples
Gets the
deleted keyfrom the key vault enabled for soft-delete. Prints out the details of thedeleted keyreturned in theHTTPresponse.Response<DeletedKey> deletedKeyResponse = keyClient.getDeletedKeyWithResponse("keyName", new Context("key1", "value1")); System.out.printf("Deleted key with recovery id: %s%n", deletedKeyResponse.getValue().getRecoveryId());- Parameters:
name- The name of the deletedkey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains thedeleted key. - Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
purgeDeletedKey
Permanently deletes the specifiedkeywithout the possibility of recovery. The purge deleted key operation is applicable for soft-delete enabled vaults. This operation requires thekeys/purgepermission.Code Samples
Purges the
deleted keyfrom the key vault enabled for soft-delete.keyClient.purgeDeletedKey("deletedKeyName");- Parameters:
name- The name of thedeleted key.- Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
purgeDeletedKeyWithResponse
public com.azure.core.http.rest.Response<Void> purgeDeletedKeyWithResponse(String name, com.azure.core.util.Context context) Permanently deletes the specifiedkeywithout the possibility of recovery. The purge deleted key operation is applicable for soft-delete enabled vaults. This operation requires thekeys/purgepermission.Code Samples
Purges the
deleted keyfrom the key vault enabled for soft-delete.Response<Void> purgeDeletedKeyResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName", new Context("key1", "value1")); System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode());- Parameters:
name- The name of thedeleted key.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsecontaining status code and HTTP headers. - Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
beginRecoverDeletedKey
public com.azure.core.util.polling.SyncPoller<KeyVaultKey, Void> beginRecoverDeletedKey(String name) Recovers thedeleted keyin the key vault to its latest version and can only be performed on a soft-delete enabled vault. An attempt to recover annon-deleted keywill return an error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires thekeys/recoverpermission.Code Samples
Recovers the
deleted keyfrom the key vault enabled for soft-delete.SyncPoller<KeyVaultKey, Void> recoverKeyPoller = keyClient.beginRecoverDeletedKey("deletedKeyName"); PollResponse<KeyVaultKey> recoverKeyPollResponse = recoverKeyPoller.poll(); KeyVaultKey recoveredKey = recoverKeyPollResponse.getValue(); System.out.printf("Recovered key name: %s%n", recoveredKey.getName()); System.out.printf("Recovered key id: %s%n", recoveredKey.getId()); // Key is being recovered on the server. recoverKeyPoller.waitForCompletion(); // Key is recovered- Parameters:
name- The name of thedeleted keyto be recovered.- Returns:
- A
SyncPollerto poll on and retrieverecovered key. - Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
backupKey
Requests a backup of the specifiedkeybe downloaded to the client. The key backup operation exports akeyfrom 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 akeyin one Azure Key Vault instance, backup thekey, and then restore it into another Azure Key Vault instance. The backup operation may be used to export, in protected form, anykey typefrom Azure Key Vault. Individual versions of akeycannot be backed up.Backup/Restorecan 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 thekey/backuppermission.Code Samples
Backs up the
keyfrom the key vault.byte[] keyBackup = keyClient.backupKey("keyName"); System.out.printf("Key backup byte array length: %s%n", keyBackup.length);- Parameters:
name- The name of thekey.- Returns:
- The backed up key blob.
- Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
backupKeyWithResponse
public com.azure.core.http.rest.Response<byte[]> backupKeyWithResponse(String name, com.azure.core.util.Context context) Requests a backup of the specifiedkeybe downloaded to the client. The key backup operation exports akeyfrom 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 akeyin one Azure Key Vault instance, backup thekey, and then restore it into another Azure Key Vault instance. The backup operation may be used to export, in protected form, anykey typefrom Azure Key Vault. Individual versions of akeycannot be backed up.Backup/Restorecan 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 thekey/backuppermission.Code Samples
Backs up the
keyfrom the key vault and prints out the length of the key's backup byte array returned in theHTTPresponse.Response<byte[]> backupKeyResponse = keyClient.backupKeyWithResponse("keyName", new Context("key1", "value1")); System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length);- Parameters:
name- The name of thekey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains the backed up key blob. - Throws:
com.azure.core.exception.HttpResponseException- When a key withnameis an empty string.com.azure.core.exception.ResourceNotFoundException- When a key withnamedoesn't exist in the key vault.
-
restoreKeyBackup
Restores a backed upkeyto a vault. Imports a previously backed upkeyinto Azure Key Vault, restoring thekey, its key identifier, attributes and access control policies. The restore operation may be used to import a previously backed upkey. Individual versions of akeycannot be restored. Thekeyis 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 thekeyis 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 therestorepermission in the target key vault. This operation requires thekeys/restorepermission.Code Samples
Restores the
// Pass the key backup byte array to the restore operation.keyin the key vault from its backup.byte[] keyBackupByteArray = {}; KeyVaultKey keyResponse = keyClient.restoreKeyBackup(keyBackupByteArray); System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getName(), keyResponse.getId());- Parameters:
backup- The backup blob associated with thekey.- Returns:
- The
restored key. - Throws:
com.azure.core.exception.ResourceModifiedException- When thebackupblob is malformed.
-
restoreKeyBackupWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> restoreKeyBackupWithResponse(byte[] backup, com.azure.core.util.Context context) Restores a backed upkeyto a vault. Imports a previously backed upkeyinto Azure Key Vault, restoring thekey, its key identifier, attributes and access control policies. The restore operation may be used to import a previously backed upkey. Individual versions of akeycannot be restored. Thekeyis 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 thekeyis 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 therestorepermission in the target key vault. This operation requires thekeys/restorepermission.Code Samples
Restores the
// Pass the key backup byte array to the restore operation.keyin the key vault from its backup. Prints out the details of therestored keyreturned in theHTTPresponse.Response<KeyVaultKey> keyResponse = keyClient.restoreKeyBackupWithResponse(keyBackupByteArray, new Context("key1", "value1")); System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getValue().getName(), keyResponse.getValue().getId());- Parameters:
backup- The backup blob associated with thekey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains therestored key. - Throws:
com.azure.core.exception.ResourceModifiedException- When thebackupblob is malformed.
-
listPropertiesOfKeys
Listkeysin the key vault. Retrieves a list of thekeysin the key vault asJsonWebKeystructures that contain the public part of a storedkey. The list operation is applicable to allkey typesand the individualkeyresponse in the list is represented byKeyPropertiesas 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 thekeys/listpermission.Code Samples
It is possible to get
full keyswith key material from this information. Loop over theKeyPropertiesand callgetKey(String, String). This will return thekeywith key material included as of its latest version.for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType()); }Iterate keys by page
It is possible to get
full keyswith key material from this information. Iterate over all theKeyPropertiesby page and callgetKey(String, String). This will return thekeywith key material included as of its latest version.keyClient.listPropertiesOfKeys().iterableByPage().forEach(pagedResponse -> { System.out.printf("Got response details. Url: %s. Status code: %d.%n", pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); pagedResponse.getElements().forEach(keyProperties -> { KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType()); }); }); -
listPropertiesOfKeys
public com.azure.core.http.rest.PagedIterable<KeyProperties> listPropertiesOfKeys(com.azure.core.util.Context context) Listkeysin the key vault. Retrieves a list of thekeysin the key vault asJsonWebKeystructures that contain the public part of a storedkey. The list operation is applicable to allkey typesand the individualkeyresponse in the list is represented byKeyPropertiesas 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 thekeys/listpermission.Code Samples
It is possible to get
full keyswith key material from this information. Loop over theKeyPropertiesand callgetKey(String, String). This will return thekeywith key material included as of its latest version.for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys(new Context("key1", "value1"))) { KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType()); }Iterate by page
It is possible to get
full keyswith key material from this information. Iterate over all theKeyPropertiesby page and callgetKey(String, String). This will return thekeywith key material included as of its latest version.keyClient.listPropertiesOfKeys().iterableByPage().forEach(pagedResponse -> { System.out.printf("Got response details. Url: %s. Status code: %d.%n", pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); pagedResponse.getElements().forEach(keyProperties -> { KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType()); }); }); -
listDeletedKeys
Listsdeleted keysof the key vault. Thedeleted keysare retrieved asJsonWebKeystructures that contain the public part of adeleted key. The get deleted keys operation is applicable for vaults enabled for soft-delete. This operation requires thekeys/listpermission.Code Samples
Lists the
deleted keysin the key vault and for eachdeleted keyprints out its recovery id.for (DeletedKey deletedKey : keyClient.listDeletedKeys()) { System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); }Code Samples to iterate over deleted keys by page
Iterates over the
deleted keysby page in the key vault and for each deleted key prints out its recovery id.keyClient.listDeletedKeys().iterableByPage().forEach(pagedResponse -> { System.out.printf("Got response details. Url: %s. Status code: %d.%n", pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); pagedResponse.getElements().forEach(deletedKey -> System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); });- Returns:
PagedIterableof all of thedeleted keysin the vault.
-
listDeletedKeys
public com.azure.core.http.rest.PagedIterable<DeletedKey> listDeletedKeys(com.azure.core.util.Context context) Listsdeleted keysof the key vault. Thedeleted keysare retrieved asJsonWebKeystructures that contain the public part of adeleted key. The get deleted keys operation is applicable for vaults enabled for soft-delete. This operation requires thekeys/listpermission.Code Samples
Lists the
deleted keysin the key vault and for eachdeleted keyprints out its recovery id.for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context("key1", "value1"))) { System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); }Code Samples to iterate over deleted keys by page
Iterates over the
deleted keysby page in the key vault and for each deleted key prints out its recovery id.keyClient.listDeletedKeys().iterableByPage().forEach(pagedResponse -> { System.out.printf("Got response details. Url: %s. Status code: %d.%n", pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); pagedResponse.getElements().forEach(deletedKey -> System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); });- Parameters:
context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
PagedIterableof all of thedeleted keysin the vault.
-
listPropertiesOfKeyVersions
public com.azure.core.http.rest.PagedIterable<KeyProperties> listPropertiesOfKeyVersions(String name) List all versions of the specifiedkeys. The individual key response in the flux is represented byKeyPropertiesas 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 thekeys/listpermission.It is possible to get
full keyswith key material for each version from this information. Loop over thekeyand callgetKey(String, String). This will return thekeyswith key material included of the specified versions.for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName")) { KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", key.getProperties().getVersion(), key.getName(), key.getKeyType()); }Code Samples to iterate over key versions by page
It is possible to get
full keyswith key material for each version from this information. Iterate over all thekeyby page and callgetKey(String, String). This will return thekeyswith key material included of the specified versions.keyClient.listPropertiesOfKeyVersions("keyName").iterableByPage().forEach(pagedResponse -> { System.out.printf("Got response details. Url: %s. Status code: %d.%n", pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); pagedResponse.getElements().forEach(keyProperties -> System.out.printf("Key name: %s. Key version: %s.%n", keyProperties.getName(), keyProperties.getVersion())); });- Parameters:
name- The name of thekey.- Returns:
PagedIterableofkeyof all the versions of the specified key in the vault. The list is empty if akeywith the providednamedoes not exist in the key vault.- Throws:
com.azure.core.exception.ResourceNotFoundException- When a given keynameisnullor an empty string.
-
listPropertiesOfKeyVersions
public com.azure.core.http.rest.PagedIterable<KeyProperties> listPropertiesOfKeyVersions(String name, com.azure.core.util.Context context) List all versions of the specifiedkeys. The individual key response in the flux is represented byKeyPropertiesas 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 thekeys/listpermission.It is possible to get
full keyswith key material for each version from this information. Loop over thekeyand callgetKey(String, String). This will return thekeyswith key material included of the specified versions.for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName", new Context("key1", "value1"))) { KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", key.getProperties().getVersion(), key.getName(), key.getKeyType()); }Code Samples to iterate over key versions by page
It is possible to get
full keyswith key material for each version from this information. Iterate over all thekeyby page and callgetKey(String, String). This will return thekeyswith key material included of the specified versions.keyClient.listPropertiesOfKeyVersions("keyName").iterableByPage().forEach(pagedResponse -> { System.out.printf("Got response details. Url: %s. Status code: %d.%n", pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); pagedResponse.getElements().forEach(keyProperties -> System.out.printf("Key name: %s. Key version: %s.%n", keyProperties.getName(), keyProperties.getVersion())); });- Parameters:
name- The name of thekey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
PagedIterableofkeyof all the versions of the specifiedkeyin the vault. The list is empty if akeywith the providednamedoes not exist in the key vault.- Throws:
com.azure.core.exception.ResourceNotFoundException- When a given keynameisnullor an empty string.
-
getRandomBytes
public byte[] getRandomBytes(int count) 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; byte[] randomBytes = keyClient.getRandomBytes(amount); System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes));- Parameters:
count- The requested number of random bytes.- Returns:
- The requested number of bytes containing random values from a managed HSM.
-
getRandomBytesWithResponse
public com.azure.core.http.rest.Response<byte[]> getRandomBytesWithResponse(int count, com.azure.core.util.Context context) 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
HTTP Responsedetails and the retrieved bytes in base64Url format.int amountOfBytes = 16; Response<byte[]> response = keyClient.getRandomBytesWithResponse(amountOfBytes, new Context("key1", "value1")); System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n", response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue()));- Parameters:
count- The requested number of random bytes.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- The
HTTP responsefor this operation and the requested number of bytes containing random values from a managed HSM.
-
releaseKey
Releases the latest version of akey.The
keymust be exportable. This operation requires thekeys/releasepermission.Code Samples
Releases a
key. Prints out the signed object that contains the release key.String targetAttestationToken = "someAttestationToken"; ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", targetAttestationToken); System.out.printf("Signed object containing released key: %s%n", releaseKeyResult);- Parameters:
name- The name of thekeyto release.targetAttestationToken- The attestation assertion for the target of thekeyrelease.- Returns:
- The key release result containing the
released key. - Throws:
IllegalArgumentException- IfnameortargetAttestationTokenarenullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
releaseKey
Releases a specific version of akey.The
keymust be exportable. This operation requires thekeys/releasepermission.Code Samples
Releases a
key. Prints out the signed object that contains the release key.String myKeyVersion = "<key-version>"; String myTargetAttestationToken = "someAttestationToken"; ReleaseKeyResult releaseKeyVersionResult = keyClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken); System.out.printf("Signed object containing released key: %s%n", releaseKeyVersionResult);- Parameters:
name- The name of thekeyto release.version- The version of the key to release. If this is empty ornull, this call is equivalent to callingreleaseKey(String, String), with the latest key version being released.targetAttestationToken- The attestation assertion for the target of thekeyrelease.- Returns:
- The key release result containing the
released key. - Throws:
IllegalArgumentException- IfnameortargetAttestationTokenarenullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
releaseKeyWithResponse
public com.azure.core.http.rest.Response<ReleaseKeyResult> releaseKeyWithResponse(String name, String version, String targetAttestationToken, ReleaseKeyOptions releaseKeyOptions, com.azure.core.util.Context context) Releases akey.The key must be exportable. This operation requires the
keys/releasepermission.Code Samples
Releases a
key. Prints out theHTTP Responsedetails and the signed object that contains the release key.String releaseKeyVersion = "<key-version>"; String someTargetAttestationToken = "someAttestationToken"; ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions() .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256) .setNonce("someNonce"); Response<ReleaseKeyResult> releaseKeyResultResponse = keyClient.releaseKeyWithResponse("keyName", releaseKeyVersion, someTargetAttestationToken, releaseKeyOptions, new Context("key1", "value1")); System.out.printf("Response received successfully with status code: %d. Signed object containing" + "released key: %s%n", releaseKeyResultResponse.getStatusCode(), releaseKeyResultResponse.getValue().getValue());- Parameters:
name- The name of thekeyto release.version- The version of thekeyto release. If this is empty ornull, this call is equivalent to callingreleaseKey(String, String), with the latest key version being released.targetAttestationToken- The attestation assertion for the target of the key release.releaseKeyOptions- Additionaloptionsfor releasing akey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- The
HTTP responsefor this operation and theReleaseKeyResultcontaining thereleased key. - Throws:
IllegalArgumentException- IfnameortargetAttestationTokenarenullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
rotateKey
Rotates akey. The rotate key operation will do so based onkey's rotation policy. This operation requires thekeys/rotatepermission.Code Samples
Rotates a
key. Prints outrotated keydetails.KeyVaultKey key = keyClient.rotateKey("keyName"); System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), key.getProperties().getVersion());- Parameters:
name- The name ofkeyto be rotated. The system will generate a new version in the specifiedkey.- Returns:
- The new version of the rotated
key. - Throws:
IllegalArgumentException- Ifnameisnullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
rotateKeyWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> rotateKeyWithResponse(String name, com.azure.core.util.Context context) Rotates akey. The rotate key operation will do so based onkey's rotation policy. This operation requires thekeys/rotatepermission.Code Samples
Rotates a
key. Prints out theHTTP Responseandrotated keydetails.Response<KeyVaultKey> keyResponse = keyClient.rotateKeyWithResponse("keyName", new Context("key1", "value1")); System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and" + "version: %s%n", keyResponse.getStatusCode(), keyResponse.getValue().getName(), keyResponse.getValue().getProperties().getVersion());- Parameters:
name- The name ofkeyto be rotated. The system will generate a new version in the specifiedkey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- The
HTTP responsefor this operation containing the new version of the rotatedkey. - Throws:
IllegalArgumentException- Ifnameisnullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
getKeyRotationPolicy
Gets theKeyRotationPolicyfor thekeywith the provided name. This operation requires thekeys/getpermission.Code Samples
Retrieves the
rotation policyof a givenkey. Prints out therotation policy keydetails.KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy("keyName"); System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId());- Parameters:
keyName- The name of thekey.- Returns:
- The
KeyRotationPolicyfor thekey. - Throws:
IllegalArgumentException- Ifnameisnullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
getKeyRotationPolicyWithResponse
public com.azure.core.http.rest.Response<KeyRotationPolicy> getKeyRotationPolicyWithResponse(String keyName, com.azure.core.util.Context context) Gets theKeyRotationPolicyfor thekeywith the provided name. This operation requires thekeys/getpermission.Code Samples
Retrieves the
rotation policyof a givenkey. Prints out theHTTP Responseandrotation policy keydetails.Response<KeyRotationPolicy> keyRotationPolicyResponse = keyClient.getKeyRotationPolicyWithResponse("keyName", new Context("key1", "value1")); System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy" + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId());- Parameters:
keyName- The name of thekey.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
HTTP responsefor this operation containing theKeyRotationPolicyfor thekey. - Throws:
IllegalArgumentException- Ifnameisnullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
updateKeyRotationPolicy
public KeyRotationPolicy updateKeyRotationPolicy(String keyName, KeyRotationPolicy keyRotationPolicy) Updates theKeyRotationPolicyof thekeywith the provided name. This operation requires thekeys/updatepermission.Code Samples
Updates the
rotation policyof a givenkey. Prints out therotation policy keydetails.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"); KeyRotationPolicy updatedPolicy = keyClient.updateKeyRotationPolicy("keyName", keyRotationPolicy); System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId());- Parameters:
keyName- The name of thekey.keyRotationPolicy- TheKeyRotationPolicyfor the kekeyy.- Returns:
- The
KeyRotationPolicyfor thekey. - Throws:
IllegalArgumentException- Ifnameisnullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
updateKeyRotationPolicyWithResponse
public com.azure.core.http.rest.Response<KeyRotationPolicy> updateKeyRotationPolicyWithResponse(String keyName, KeyRotationPolicy keyRotationPolicy, com.azure.core.util.Context context) Updates theKeyRotationPolicyof the key with the provided name. This operation requires thekeys/updatepermission.Code Samples
Updates the
rotation policyof a givenkey. Prints out theHTTP Responseandrotation policy keydetails.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"); Response<KeyRotationPolicy> keyRotationPolicyResponse = keyClient.updateKeyRotationPolicyWithResponse( "keyName", myKeyRotationPolicy, new Context("key1", "value1")); System.out.printf("Response received successfully with status code: %d. Updated key rotation policy" + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId());- Parameters:
keyName- The name of thekey.keyRotationPolicy- TheKeyRotationPolicyfor the key.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
HTTP responsefor this operation containing theKeyRotationPolicyfor thekey. - Throws:
IllegalArgumentException- Ifnameisnullor empty.com.azure.core.exception.ResourceNotFoundException- If thekeyfor the providednamedoes not exist.
-
getKeyAttestation
Gets the public part of the latest version of the specifiedkey, including its key attestation information. The get key operation is applicable to allkey typesand it requires thekeys/getpermission.Code Samples
Gets the latest version of the
keyin the key vault, including its attestation information. Prints out the details of theretrieved key.KeyVaultKey keyVaultKey = keyClient.getKeyAttestation("keyName"); System.out.printf("Retrieved key with name: %s and: id %s%n", keyVaultKey.getName(), keyVaultKey.getId()); KeyAttestation keyAttestationInfo = keyVaultKey.getProperties().getKeyAttestation(); System.out.printf("Attestation information details: %n" + "Certificate PEM file: %s%n" + "Private key attestation: %s%n" + "Public key attestation: %s%n" + "Version: %s", Base64Url.encode(keyAttestationInfo.getCertificatePemFile()), Base64Url.encode(keyAttestationInfo.getPrivateKeyAttestation()), Base64Url.encode(keyAttestationInfo.getPublicKeyAttestation()), keyAttestationInfo.getVersion());- Parameters:
name- The name of thekey, cannot benull.- Returns:
- The requested
key. The content of thekeyisnullif bothnameandversionarenullor empty. - Throws:
com.azure.core.exception.HttpResponseException- If a validnameand a non-null/emptyversionis specified.com.azure.core.exception.ResourceNotFoundException- When akeywith the providednamedoesn't exist in the key vault or an empty/nullnameand a non-null/emptyversionis provided.
-
getKeyAttestationWithResponse
public com.azure.core.http.rest.Response<KeyVaultKey> getKeyAttestationWithResponse(String name, String version, com.azure.core.util.Context context) Gets the public part of the specifiedkeyand key version, including its key attestation information. The get key operation is applicable to allkey typesand it requires thekeys/getpermission.Code Samples
Gets a specific version of the
keyin the key vault, including its attestation information. Prints out the details of theretrieved key.String keyVersion = "<key-version>"; Response<KeyVaultKey> getKeyResponse = keyClient.getKeyAttestationWithResponse("keyName", keyVersion, new Context("key1", "value1")); KeyVaultKey keyVaultKey = getKeyResponse.getValue(); System.out.printf("Retrieved key with name: %s and: id %s%n", keyVaultKey.getName(), keyVaultKey.getId()); KeyAttestation keyAttestationInfo = keyVaultKey.getProperties().getKeyAttestation(); System.out.printf("Attestation information details: %n" + "Certificate PEM file: %s%n" + "Private key attestation: %s%n" + "Public key attestation: %s%n" + "Version: %s", Base64Url.encode(keyAttestationInfo.getCertificatePemFile()), Base64Url.encode(keyAttestationInfo.getPrivateKeyAttestation()), Base64Url.encode(keyAttestationInfo.getPublicKeyAttestation()), keyAttestationInfo.getVersion());- Parameters:
name- The name of thekey, cannot benull.version- The version of thekeyto retrieve. If this is an empty string ornull, this call is equivalent to callinggetKey(String), with the latest version being retrieved.context- AdditionalContextthat is passed through theHttpPipelineduring the service call.- Returns:
- A
Responsewhosevaluecontains the requestedkey. The content of thekeyisnullif bothnameandversionarenullor empty. - Throws:
com.azure.core.exception.HttpResponseException- If a validnameand a non-null/emptyversionis specified.com.azure.core.exception.ResourceNotFoundException- When akeywith the providednamedoesn't exist in the key vault or an empty/nullnameand a non-null/emptyversionis provided.
-