azure-security-keyvault-keys-java

Azure Key Vault Keys Java SDK for cryptographic key management. Use when creating, managing, or using RSA/EC keys, performing encrypt/decrypt/sign/verify operations, or working with HSM-backed keys.

npx skills add https://github.com/microsoft/skills --skill azure-security-keyvault-keys-java

Azure Key Vault Keys (Java)

Manage cryptographic keys and perform cryptographic operations in Azure Key Vault and Managed HSM.

Installation

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-security-keyvault-keys</artifactId>
    <version>4.9.0</version>
</dependency>

Client Creation

import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
import com.azure.security.keyvault.keys.KeyClient;
import com.azure.security.keyvault.keys.KeyClientBuilder;
import com.azure.security.keyvault.keys.cryptography.CryptographyClient;
import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

// Key management client
KeyClient keyClient = new KeyClientBuilder()
    .vaultUrl("https://<vault-name>.vault.azure.net")
    .credential(credential)
    .buildClient();

// Async client
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
    .vaultUrl("https://<vault-name>.vault.azure.net")
    .credential(credential)
    .buildAsyncClient();

// Cryptography client (for encrypt/decrypt/sign/verify)
CryptographyClient cryptoClient = new CryptographyClientBuilder()
    .keyIdentifier("https://<vault-name>.vault.azure.net/keys/<key-name>/<key-version>")
    .credential(credential)
    .buildClient();

Key Types

TypeDescription
RSARSA key (2048, 3072, 4096 bits)
RSA_HSMRSA key in HSM
ECElliptic Curve key
EC_HSMElliptic Curve key in HSM
OCTSymmetric key (Managed HSM only)
OCT_HSMSymmetric key in HSM

Create Keys

Create RSA Key

import com.azure.security.keyvault.keys.models.*;

// Simple RSA key
KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("my-rsa-key")
    .setKeySize(2048));

System.out.println("Key name: " + rsaKey.getName());
System.out.println("Key ID: " + rsaKey.getId());
System.out.println("Key type: " + rsaKey.getKeyType());

// RSA key with options
KeyVaultKey rsaKeyWithOptions = keyClient.createRsaKey(new CreateRsaKeyOptions("my-rsa-key-2")
    .setKeySize(4096)
    .setExpiresOn(OffsetDateTime.now().plusYears(1))
    .setNotBefore(OffsetDateTime.now())
    .setEnabled(true)
    .setKeyOperations(KeyOperation.ENCRYPT, KeyOperation.DECRYPT, 
                       KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY)
    .setTags(Map.of("environment", "production")));

// HSM-backed RSA key
KeyVaultKey hsmKey = keyClient.createRsaKey(new CreateRsaKeyOptions("my-hsm-key")
    .setKeySize(2048)
    .setHardwareProtected(true));

Create EC Key

// EC key with P-256 curve
KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("my-ec-key")
    .setCurveName(KeyCurveName.P_256));

// EC key with other curves
KeyVaultKey ecKey384 = keyClient.createEcKey(new CreateEcKeyOptions("my-ec-key-384")
    .setCurveName(KeyCurveName.P_384));

KeyVaultKey ecKey521 = keyClient.createEcKey(new CreateEcKeyOptions("my-ec-key-521")
    .setCurveName(KeyCurveName.P_521));

// HSM-backed EC key
KeyVaultKey ecHsmKey = keyClient.createEcKey(new CreateEcKeyOptions("my-ec-hsm-key")
    .setCurveName(KeyCurveName.P_256)
    .setHardwareProtected(true));

Create Symmetric Key (Managed HSM only)

KeyVaultKey octKey = keyClient.createOctKey(new CreateOctKeyOptions("my-symmetric-key")
    .setKeySize(256)
    .setHardwareProtected(true));

Get Key

// Get latest version
KeyVaultKey key = keyClient.getKey("my-key");

// Get specific version
KeyVaultKey keyVersion = keyClient.getKey("my-key", "<version-id>");

// Get only key properties (no key material)
KeyProperties keyProps = keyClient.getKey("my-key").getProperties();

Update Key Properties

KeyVaultKey key = keyClient.getKey("my-key");

// Update properties
key.getProperties()
    .setEnabled(false)
    .setExpiresOn(OffsetDateTime.now().plusMonths(6))
    .setTags(Map.of("status", "archived"));

KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties(),
    KeyOperation.ENCRYPT, KeyOperation.DECRYPT);

List Keys

import com.azure.core.util.paging.PagedIterable;

// List all keys
for (KeyProperties keyProps : keyClient.listPropertiesOfKeys()) {
    System.out.println("Key: " + keyProps.getName());
    System.out.println("  Enabled: " + keyProps.isEnabled());
    System.out.println("  Created: " + keyProps.getCreatedOn());
}

// List key versions
for (KeyProperties version : keyClient.listPropertiesOfKeyVersions("my-key")) {
    System.out.println("Version: " + version.getVersion());
    System.out.println("Created: " + version.getCreatedOn());
}

Delete Key

import com.azure.core.util.polling.SyncPoller;

// Begin delete (soft-delete enabled vaults)
SyncPoller<DeletedKey, Void> deletePoller = keyClient.beginDeleteKey("my-key");

// Wait for deletion
DeletedKey deletedKey = deletePoller.poll().getValue();
System.out.println("Deleted: " + deletedKey.getDeletedOn());

deletePoller.waitForCompletion();

// Purge deleted key (permanent deletion)
keyClient.purgeDeletedKey("my-key");

// Recover deleted key
SyncPoller<KeyVaultKey, Void> recoverPoller = keyClient.beginRecoverDeletedKey("my-key");
recoverPoller.waitForCompletion();

Cryptographic Operations

Encrypt/Decrypt

import com.azure.security.keyvault.keys.cryptography.models.*;

CryptographyClient cryptoClient = new CryptographyClientBuilder()
    .keyIdentifier("https://<vault>.vault.azure.net/keys/<key-name>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

byte[] plaintext = "Hello, World!".getBytes(StandardCharsets.UTF_8);

// Encrypt
EncryptResult encryptResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext);
byte[] ciphertext = encryptResult.getCipherText();
System.out.println("Ciphertext length: " + ciphertext.length);

// Decrypt
DecryptResult decryptResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext);
String decrypted = new String(decryptResult.getPlainText(), StandardCharsets.UTF_8);
System.out.println("Decrypted: " + decrypted);

Sign/Verify

import java.security.MessageDigest;

// Create digest of data
byte[] data = "Data to sign".getBytes(StandardCharsets.UTF_8);
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(data);

// Sign
SignResult signResult = cryptoClient.sign(SignatureAlgorithm.RS256, digest);
byte[] signature = signResult.getSignature();

// Verify
VerifyResult verifyResult = cryptoClient.verify(SignatureAlgorithm.RS256, digest, signature);
System.out.println("Valid signature: " + verifyResult.isValid());

Wrap/Unwrap Key

// Key to wrap (e.g., AES key)
byte[] keyToWrap = new byte[32];  // 256-bit key
new SecureRandom().nextBytes(keyToWrap);

// Wrap
WrapResult wrapResult = cryptoClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap);
byte[] wrappedKey = wrapResult.getEncryptedKey();

// Unwrap
UnwrapResult unwrapResult = cryptoClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrappedKey);
byte[] unwrappedKey = unwrapResult.getKey();

Backup and Restore

// Backup
byte[] backup = keyClient.backupKey("my-key");

// Save backup to file
Files.write(Paths.get("key-backup.blob"), backup);

// Restore
byte[] backupData = Files.readAllBytes(Paths.get("key-backup.blob"));
KeyVaultKey restoredKey = keyClient.restoreKeyBackup(backupData);

Key Rotation

// Rotate to new version
KeyVaultKey rotatedKey = keyClient.rotateKey("my-key");
System.out.println("New version: " + rotatedKey.getProperties().getVersion());

// Set rotation policy
KeyRotationPolicy policy = new KeyRotationPolicy()
    .setExpiresIn("P90D")  // Expire after 90 days
    .setLifetimeActions(Arrays.asList(
        new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
            .setTimeBeforeExpiry("P30D")));  // Rotate 30 days before expiry

keyClient.updateKeyRotationPolicy("my-key", policy);

// Get rotation policy
KeyRotationPolicy currentPolicy = keyClient.getKeyRotationPolicy("my-key");

Import Key

import com.azure.security.keyvault.keys.models.ImportKeyOptions;
import com.azure.security.keyvault.keys.models.JsonWebKey;

// Import existing key material
JsonWebKey jsonWebKey = new JsonWebKey()
    .setKeyType(KeyType.RSA)
    .setN(modulus)
    .setE(exponent)
    .setD(privateExponent)
    // ... other RSA components
    ;

ImportKeyOptions importOptions = new ImportKeyOptions("imported-key", jsonWebKey)
    .setHardwareProtected(false);

KeyVaultKey importedKey = keyClient.importKey(importOptions);

Encryption Algorithms

AlgorithmKey TypeDescription
RSA1_5RSARSAES-PKCS1-v1_5
RSA_OAEPRSARSAES with OAEP (recommended)
RSA_OAEP_256RSARSAES with OAEP using SHA-256
A128GCMOCTAES-GCM 128-bit
A256GCMOCTAES-GCM 256-bit
A128CBCOCTAES-CBC 128-bit
A256CBCOCTAES-CBC 256-bit

Signature Algorithms

AlgorithmKey TypeHash
RS256RSASHA-256
RS384RSASHA-384
RS512RSASHA-512
PS256RSASHA-256 (PSS)
ES256EC P-256SHA-256
ES384EC P-384SHA-384
ES512EC P-521SHA-512

Error Handling

import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceNotFoundException;

try {
    KeyVaultKey key = keyClient.getKey("non-existent-key");
} catch (ResourceNotFoundException e) {
    System.out.println("Key not found: " + e.getMessage());
} catch (HttpResponseException e) {
    System.out.println("HTTP error " + e.getResponse().getStatusCode());
    System.out.println("Message: " + e.getMessage());
}

Environment Variables

AZURE_KEYVAULT_URL=https://<vault-name>.vault.azure.net  # Required for vault URL
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production

Best Practices

  1. Use HSM Keys for Production - Set setHardwareProtected(true) for sensitive keys
  2. Enable Soft Delete - Protects against accidental deletion
  3. Key Rotation - Set up automatic rotation policies
  4. Least Privilege - Use separate keys for different operations
  5. Local Crypto When Possible - Use CryptographyClient with local key material to reduce round-trips

Trigger Phrases

  • "Key Vault keys Java", "cryptographic keys Java"
  • "encrypt decrypt Java", "sign verify Java"
  • "RSA key", "EC key", "HSM key"
  • "key rotation", "wrap unwrap key"

Plus de skills de microsoft

oss-growth
microsoft
Persona de growth hacker OSS
agent-framework-azure-ai-py
microsoft
Créez des agents Azure AI Foundry à l’aide du SDK Python Microsoft Agent Framework (agent-framework-azure-ai). À utiliser lors de la création d’agents persistants avec AzureAIAgentsProvider, de l’utilisation d’outils hébergés (interpréteur de code, recherche de fichiers, recherche web), de l’intégration de serveurs MCP, de la gestion de fils de conversation ou de l’implémentation de réponses en streaming. Couvre les outils de fonction, les sorties structurées et les agents multi-outils.
development
airunway-aks-setup
microsoft
Configurez AI Runway sur AKS — du cluster nu au modèle en cours d'exécution. Couvre la vérification du cluster, l'installation du contrôleur, l'évaluation GPU, la configuration du fournisseur et le premier déploiement. QUAND : « configurer AI Runway », « intégrer un cluster AKS », « installer AI Runway », « configuration airunway », « déployer un modèle sur AKS », « inférence GPU sur AKS », « configuration KAITO sur AKS », « exécuter LLM sur AKS », « vLLM sur AKS », « configurer le service de modèles sur AKS », « contrôleur AI Runway ».
devops
appinsights-instrumentation
microsoft
Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrument app, App Insights SDK, telemetry patterns, what is App Insights, Application Insights guidance, instrumentation examples, APM best practices.
devops
applicationinsights-web-ts
microsoft
Instrumentez les applications navigateur/web avec le SDK JavaScript Application Insights (@microsoft/applicationinsights-web). Utilisez-le pour la surveillance des utilisateurs réels (RUM) — vues de page, clics, dépendances AJAX/fetch, exceptions, événements personnalisés et traces d’agents GenAI côté navigateur corrélées aux traces OpenTelemetry backend. Couvre le script de chargement du SDK et la configuration npm, les extensions de framework (React, React Native, Angular), Click Analytics, les initialiseurs de télémétrie et les conventions sémantiques OTel GenAI pour les spans d’agents/outils/modèles émises depuis le navigateur.
devops
azure-ai-anomalydetector-java
microsoft
Créez des applications de détection d'anomalies avec le SDK Azure AI Anomaly Detector pour Java. Utilisez-le lors de l'implémentation de la détection d'anomalies univariées/multivariées, de l'analyse de séries temporelles ou de la surveillance basée sur l'IA.
development
azure-ai-language-conversations-py
microsoft
Implémentez la compréhension du langage conversationnel (CLU) à l’aide du SDK Python azure-ai-language-conversations. Utilisez-le lorsque vous travaillez avec ConversationAnalysisClient pour analyser l’intention et les entités d’une conversation, créer des fonctionnalités de NLP ou intégrer la compréhension du langage dans des applications.
development
azure-ai-ml-py
microsoft
SDK v2 d’Azure Machine Learning pour Python. Utiliser pour les espaces de travail ML, les tâches, les modèles, les jeux de données, le calcul et les pipelines. Déclencheurs : « azure-ai-ml », « MLClient », « espace de travail », « registre de modèles », « tâches d’entraînement », « jeux de données ».
development