From 1b7c764764b560effa52ae5c89b129c299261aa4 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Fri, 24 Jan 2025 06:54:44 +0000 Subject: [PATCH] CodeGen from PR 3609 in test-repo-billy/azure-rest-api-specs Merge 0381f6176c640230cb2c2779f333316fdc44c436 into f39c04630cbd7b70c5a369f83f5485484cf1683d --- .../azure-security-keyvault-keys/CHANGELOG.md | 903 ---- .../azure-security-keyvault-keys/README.md | 373 -- .../TROUBLESHOOTING.md | 2 - .../azure-security-keyvault-keys/assets.json | 6 - .../checkstyle-suppressions.xml | 39 - .../migration_guide.md | 303 -- .../azure-security-keyvault-keys/pom.xml | 86 - .../spotbugs-exclude.xml | 99 - .../keyvault/keys/KeyAsyncClient.java | 2077 -------- .../security/keyvault/keys/KeyClient.java | 2107 -------- .../keyvault/keys/KeyClientBuilder.java | 511 -- .../keyvault/keys/KeyServiceVersion.java | 69 - .../cryptography/CryptographyAsyncClient.java | 907 ---- .../keys/cryptography/CryptographyClient.java | 1233 ----- .../CryptographyClientBuilder.java | 593 --- .../CryptographyServiceVersion.java | 69 - .../KeyEncryptionKeyAsyncClient.java | 96 - .../cryptography/KeyEncryptionKeyClient.java | 82 - .../KeyEncryptionKeyClientBuilder.java | 480 -- .../implementation/Aes128Cbc.java | 14 - .../implementation/Aes128CbcHmacSha256.java | 13 - .../implementation/Aes128CbcPad.java | 13 - .../cryptography/implementation/Aes128Kw.java | 41 - .../implementation/Aes192Cbc.java | 14 - .../implementation/Aes192CbcHmacSha384.java | 13 - .../implementation/Aes192CbcPad.java | 13 - .../cryptography/implementation/Aes192Kw.java | 41 - .../implementation/Aes256Cbc.java | 14 - .../implementation/Aes256CbcHmacSha512.java | 13 - .../implementation/Aes256CbcPad.java | 13 - .../cryptography/implementation/Aes256Kw.java | 39 - .../cryptography/implementation/AesCbc.java | 112 - .../implementation/AesCbcHmacSha2.java | 251 - .../implementation/AesCbcPad.java | 112 - .../AesKeyCryptographyClient.java | 489 -- .../cryptography/implementation/AesKw.java | 197 - .../implementation/Algorithm.java | 32 - .../implementation/AlgorithmResolver.java | 57 - .../Asn1DerSignatureEncoding.java | 190 - .../AsymmetricEncryptionAlgorithm.java | 80 - .../AsymmetricSignatureAlgorithm.java | 12 - .../CryptographyClientImpl.java | 405 -- .../implementation/CryptographyUtils.java | 231 - .../EcKeyCryptographyClient.java | 335 -- .../cryptography/implementation/Ecdsa.java | 66 - .../cryptography/implementation/Es256.java | 18 - .../cryptography/implementation/Es256k.java | 18 - .../cryptography/implementation/Es384.java | 18 - .../cryptography/implementation/Es512.java | 18 - .../implementation/HashAlgorithm.java | 25 - .../IAuthenticatedCryptoTransform.java | 9 - .../implementation/ICryptoTransform.java | 45 - .../implementation/ISignatureTransform.java | 13 - .../LocalEncryptionAlgorithm.java | 16 - .../LocalKeyCryptographyClient.java | 76 - .../implementation/LocalKeyWrapAlgorithm.java | 124 - .../LocalSignatureAlgorithm.java | 12 - .../cryptography/implementation/Rsa15.java | 100 - .../implementation/RsaEncryption.java | 12 - .../RsaKeyCryptographyClient.java | 454 -- .../cryptography/implementation/RsaOaep.java | 100 - .../implementation/SignatureEncoding.java | 42 - .../implementation/SignatureHashResolver.java | 46 - .../SymmetricEncryptionAlgorithm.java | 86 - .../implementation/package-info.java | 7 - .../models/DecryptParameters.java | 330 -- .../cryptography/models/DecryptResult.java | 64 - .../models/EncryptParameters.java | 369 -- .../cryptography/models/EncryptResult.java | 123 - .../models/EncryptionAlgorithm.java | 135 - .../cryptography/models/KeyWrapAlgorithm.java | 75 - .../keys/cryptography/models/SignResult.java | 64 - .../models/SignatureAlgorithm.java | 95 - .../cryptography/models/UnwrapResult.java | 68 - .../cryptography/models/VerifyResult.java | 63 - .../keys/cryptography/models/WrapResult.java | 64 - .../cryptography/models/package-info.java | 8 - .../keys/cryptography/package-info.java | 135 - .../keys/implementation/DeletedKeyHelper.java | 50 - .../keys/implementation/KeyClientImpl.java | 4639 ----------------- .../implementation/KeyPropertiesHelper.java | 74 - .../KeyRotationLifetimeActionHelper.java | 45 - .../KeyRotationPolicyHelper.java | 39 - .../KeyVaultCredentialPolicy.java | 526 -- .../KeyVaultErrorCodeStrings.java | 10 - .../implementation/KeyVaultKeyHelper.java | 35 - .../implementation/KeyVaultKeysUtils.java | 181 - .../implementation/SecretMinClientImpl.java | 245 - .../implementation/models/Attributes.java | 226 - .../models/BackupKeyResult.java | 78 - .../models/DeletedKeyBundle.java | 194 - .../implementation/models/DeletedKeyItem.java | 182 - .../models/DeletedKeyListResult.java | 93 - .../models/DeletionRecoveryLevel.java | 99 - .../keys/implementation/models/Error.java | 105 - .../models/GetRandomBytesRequest.java | 86 - .../implementation/models/JsonWebKey.java | 613 --- .../models/JsonWebKeyEncryptionAlgorithm.java | 116 - .../models/JsonWebKeySignatureAlgorithm.java | 97 - .../implementation/models/KeyAttributes.java | 231 - .../keys/implementation/models/KeyBundle.java | 201 - .../models/KeyCreateParameters.java | 293 -- .../models/KeyExportParameters.java | 146 - .../models/KeyImportParameters.java | 200 - .../keys/implementation/models/KeyItem.java | 173 - .../implementation/models/KeyListResult.java | 92 - .../models/KeyOperationResult.java | 154 - .../models/KeyOperationsParameters.java | 236 - .../implementation/models/KeyProperties.java | 204 - .../models/KeyReleaseParameters.java | 143 - .../models/KeyReleasePolicy.java | 157 - .../models/KeyRestoreParameters.java | 97 - .../models/KeyRotationPolicy.java | 139 - .../models/KeyRotationPolicyAttributes.java | 131 - .../models/KeySignParameters.java | 129 - .../models/KeyUpdateParameters.java | 178 - .../implementation/models/KeyVaultError.java | 73 - .../models/KeyVaultErrorException.java | 42 - .../models/KeyVaultKeysModelsUtils.java | 262 - .../models/KeyVerifyParameters.java | 165 - .../models/KeyVerifyResult.java | 73 - .../models/LifetimeActions.java | 113 - .../models/LifetimeActionsTrigger.java | 119 - .../models/LifetimeActionsType.java | 86 - .../implementation/models/RandomBytes.java | 97 - .../keys/implementation/models/SecretKey.java | 184 - .../models/SecretProperties.java | 380 -- .../models/SecretRequestAttributes.java | 221 - .../models/SecretRequestParameters.java | 160 - .../implementation/models/package-info.java | 9 - .../keys/implementation/package-info.java | 9 - .../keys/models/CreateEcKeyOptions.java | 178 - .../keys/models/CreateKeyOptions.java | 250 - .../keys/models/CreateOctKeyOptions.java | 178 - .../keys/models/CreateRsaKeyOptions.java | 206 - .../keyvault/keys/models/DeletedKey.java | 197 - .../keys/models/ImportKeyOptions.java | 108 - .../keyvault/keys/models/JsonWebKey.java | 1209 ----- .../keyvault/keys/models/KeyCurveName.java | 61 - .../models/KeyExportEncryptionAlgorithm.java | 56 - .../keyvault/keys/models/KeyOperation.java | 76 - .../keyvault/keys/models/KeyProperties.java | 446 -- .../keys/models/KeyReleasePolicy.java | 182 - .../models/KeyRotationLifetimeAction.java | 159 - .../keys/models/KeyRotationPolicy.java | 167 - .../keys/models/KeyRotationPolicyAction.java | 56 - .../keyvault/keys/models/KeyType.java | 71 - .../keyvault/keys/models/KeyVaultKey.java | 180 - .../keys/models/KeyVaultKeyIdentifier.java | 105 - .../keys/models/ReleaseKeyOptions.java | 72 - .../keys/models/ReleaseKeyResult.java | 73 - .../keyvault/keys/models/package-info.java | 9 - .../security/keyvault/keys/package-info.java | 171 - .../src/main/java/module-info.java | 22 - .../proxy-config.json | 8 - .../reflect-config.json | 746 --- .../resource-config.json | 13 - .../resources/azure-key-vault-keys.properties | 2 - .../src/samples/README.md | 113 - .../keys/BackupAndRestoreOperations.java | 105 - .../keys/BackupAndRestoreOperationsAsync.java | 104 - .../security/keyvault/keys/HelloWorld.java | 90 - .../keyvault/keys/HelloWorldAsync.java | 104 - .../KeyAsyncClientJavaDocCodeSnippets.java | 640 --- .../keys/KeyClientJavaDocCodeSnippets.java | 662 --- .../security/keyvault/keys/KeyRotation.java | 73 - .../keyvault/keys/KeyRotationAsync.java | 73 - .../keyvault/keys/ListOperations.java | 72 - .../keyvault/keys/ListOperationsAsync.java | 91 - .../keyvault/keys/ManagingDeletedKeys.java | 111 - .../keys/ManagingDeletedKeysAsync.java | 120 - .../security/keyvault/keys/ReadmeSamples.java | 264 - ...ographyAsyncClientJavaDocCodeSnippets.java | 280 - ...CryptographyClientJavaDocCodeSnippets.java | 355 -- .../EncryptDecryptOperations.java | 53 - .../EncryptDecryptOperationsAsync.java | 53 - .../cryptography/KeyWrapUnwrapOperations.java | 62 - .../KeyWrapUnwrapOperationsAsync.java | 60 - .../cryptography/SignVerifyOperations.java | 72 - .../SignVerifyOperationsAsync.java | 73 - .../keys/KeyAsyncClientManagedHsmTest.java | 136 - .../keyvault/keys/KeyAsyncClientTest.java | 830 --- .../keyvault/keys/KeyClientBuilderTest.java | 183 - .../keys/KeyClientManagedHsmTest.java | 140 - .../keys/KeyClientManagedHsmTestBase.java | 24 - .../security/keyvault/keys/KeyClientTest.java | 763 --- .../keyvault/keys/KeyClientTestBase.java | 679 --- .../keys/KeyVaultCredentialPolicyTest.java | 661 --- .../KeyVaultKeysUserAgentPropertiesTest.java | 22 - .../security/keyvault/keys/TestUtils.java | 69 - .../CryptographyClientBuilderTest.java | 224 - .../CryptographyClientManagedHsmTest.java | 22 - .../cryptography/CryptographyClientTest.java | 433 -- .../CryptographyClientTestBase.java | 341 -- .../KeyEncryptionKeyClientBuilderTest.java | 43 - .../KeyEncryptionKeyClientManagedHsmTest.java | 202 - .../KeyEncryptionKeyClientTest.java | 337 -- .../KeyEncryptionKeyClientTestBase.java | 140 - .../keys/cryptography/TestHelper.java | 75 - .../models/KeyVaultKeyIdentifierTest.java | 55 - .../swagger/autorest.md | 84 - .../swagger/pom.xml | 21 - .../src/main/java/KeysCustomizations.java | 39 - .../tsp-location.yaml | 5 + 204 files changed, 5 insertions(+), 42461 deletions(-) delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/README.md delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/TROUBLESHOOTING.md delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/assets.json delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/migration_guide.md delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/pom.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/spotbugs-exclude.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilder.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Cbc.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcHmacSha256.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcPad.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Kw.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Cbc.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcHmacSha384.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcPad.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Kw.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Cbc.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcHmacSha512.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcPad.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Kw.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbc.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcHmacSha2.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcPad.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKeyCryptographyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKw.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Algorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AlgorithmResolver.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Asn1DerSignatureEncoding.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricEncryptionAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricSignatureAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyUtils.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/EcKeyCryptographyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Ecdsa.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256k.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es384.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es512.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/HashAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/IAuthenticatedCryptoTransform.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ICryptoTransform.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ISignatureTransform.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalEncryptionAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyCryptographyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyWrapAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalSignatureAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Rsa15.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaEncryption.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaKeyCryptographyClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaOaep.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureEncoding.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureHashResolver.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SymmetricEncryptionAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptionAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/KeyWrapAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignatureAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/UnwrapResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/VerifyResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/WrapResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/DeletedKeyHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyPropertiesHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationLifetimeActionHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationPolicyHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultErrorCodeStrings.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeyHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/SecretMinClientImpl.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretKey.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretProperties.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestAttributes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateEcKeyOptions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateKeyOptions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateOctKeyOptions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateRsaKeyOptions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/DeletedKey.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ImportKeyOptions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/JsonWebKey.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyProperties.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyReleasePolicy.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationLifetimeAction.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicy.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKey.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifier.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyOptions.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/proxy-config.json delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/reflect-config.json delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-key-vault-keys.properties delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyAsyncClientJavaDocCodeSnippets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyClientJavaDocCodeSnippets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotation.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotationAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClientJavaDocCodeSnippets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientJavaDocCodeSnippets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientManagedHsmTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientBuilderTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTestBase.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/TestUtils.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilderTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientManagedHsmTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilderTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientManagedHsmTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTestBase.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/TestHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifierTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/swagger/autorest.md delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/swagger/pom.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java create mode 100644 sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml diff --git a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md deleted file mode 100644 index db9d7db6de87..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md +++ /dev/null @@ -1,903 +0,0 @@ -# Release History - -## 4.10.0-beta.1 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 4.9.2 (2025-01-14) - -### Bugs Fixed -- Fixed issue where certain `toString()` calls could cause a `NullPointerException`. ([#43776](https://github.com/Azure/azure-sdk-for-java/pull/43776)) - -## 4.9.1 (2024-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.53.0` to version `1.54.1`. -- Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. - -## 4.9.0 (2024-10-15) -- Added a new configuration flag to cryptography clients that allows deferring all cryptographic operations to the Key Vault service. ([#40384](https://github.com/Azure/azure-sdk-for-java/pull/40384)) -- Added support for Continuous Access Evaluation (CAE). ([#41814](https://github.com/Azure/azure-sdk-for-java/pull/41814)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.52.0` to version `1.53.0`. -- Upgraded `azure-core-http-netty` from `1.15.4` to version `1.15.5`. - -## 4.8.8 (2024-09-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` from `1.2.0` to version `1.3.0`. -- Upgraded `azure-core-http-netty` from `1.15.3` to version `1.15.4`. -- Upgraded `azure-core` from `1.51.0` to version `1.52.0`. - -## 4.8.7 (2024-08-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.50.0` to version `1.51.0`. -- Upgraded `azure-core-http-netty` from `1.15.2` to version `1.15.3`. - - -## 4.9.0-beta.1 (2024-07-29) - -### Features Added -- Added a new configuration flag to cryptography clients to defer all cryptographic operations to the Key Vault service. ([#40384](https://github.com/Azure/azure-sdk-for-java/pull/40384)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.49.1` to version `1.50.0`. -- Upgraded `azure-core-http-netty` from `1.15.1` to version `1.15.2`. - -## 4.8.6 (2024-07-29) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.15.1` to version `1.15.2`. -- Upgraded `azure-json` from `1.1.0` to version `1.2.0`. -- Upgraded `azure-core` from `1.49.1` to version `1.50.0`. - -## 4.8.5 (2024-06-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.49.0` to version `1.49.1`. -- Upgraded `azure-core-http-netty` from `1.15.0` to version `1.15.1`. - -## 4.8.4 (2024-05-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.48.0` to version `1.49.0`. -- Upgraded `azure-core-http-netty` from `1.14.2` to version `1.15.0`. - -## 4.8.3 (2024-04-30) - -### Other Changes - -- No changes but only upgrade version to fix Microsoft Doc. - -## 4.8.2 (2024-04-09) - -### Bugs Fixed -- Fixed issue where `hsmPlatform` was not being set in `KeyProperties`. ([#39537](https://github.com/Azure/azure-sdk-for-java/pull/39537)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.47.0` to version `1.48.0`. -- Upgraded `azure-core-http-netty` from `1.14.1` to version `1.14.2`. - -## 4.8.1 (2024-03-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.46.0` to version `1.47.0`. -- Upgraded `azure-core-http-netty` from `1.14.0` to version `1.14.1`. - -## 4.8.0 (2024-02-22) -Changes when compared to the last stable release (`4.7.3`) include: - -### Features Added -- Added support for service version `7.5`. -- Added `KeyProperties.getHsmPlatform()` to get the underlying HSM platform that a key was generated with. - -- Added fallback logic to use service-side cryptography if a key cannot be retrieved for local operations. ([#38334](https://github.com/Azure/azure-sdk-for-java/pull/38334)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.45.1` to version `1.46.0`. -- Upgraded `azure-core-http-netty` from `1.13.11` to version `1.14.0`. - -## 4.7.3 (2023-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.10` to version `1.13.11`. -- Upgraded `azure-core` from `1.45.0` to version `1.45.1`. - -## 4.7.2 (2023-11-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. - -## 4.8.0-beta.1 (2023-11-09) - -### Features Added -- Added support for service version `7.5-preview.1`. -- Added `KeyProperties.getHsmPlatform()` to get the underlying HSM platform that a key was generated with. - -#### Dependency Updates -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. - -## 4.7.1 (2023-10-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.43.0` to version `1.44.1`. -- Upgraded `azure-core-http-netty` from `1.13.7` to version `1.13.9`. - -## 4.7.0 (2023-09-25) - -### Bugs fixed -- Added a fallback mechanism to use service-side cryptography if not possible to perform operations locally. ([#36657](https://github.com/Azure/azure-sdk-for-java/pull/36657)) - -### Other Changes -- Due to internal client changes, made `KeyEncryptionKeyClient` extend `CryptographyClient`, mirroring their async counterparts. Functionality remains intact. -- Migrate test recordings to assets repo. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.42.0` to version `1.43.0`. -- Upgraded `azure-core-http-netty` from `1.13.6` to version `1.13.7`. - -## 4.6.5 (2023-08-21) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.41.0` to version `1.42.0`. -- Upgraded `azure-core-http-netty` from `1.13.5` to version `1.13.6`. - -## 4.6.4 (2023-07-25) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.40.0` to version `1.41.0`. -- Upgraded `azure-core-http-netty` from `1.13.4` to version `1.13.5`. - -## 4.6.3 (2023-06-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.39.0` to version `1.40.0`. -- Upgraded `azure-core-http-netty` from `1.13.3` to version `1.13.4`. - -## 4.6.2 (2023-05-23) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.2` to version `1.13.3`. -- Upgraded `azure-core` from `1.38.0` to version `1.39.0`. - -## 4.6.1 (2023-04-20) - -### Other Changes - -- Test proxy server migration. -- Made all logger instances static. - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.1` to version `1.13.2`. -- Upgraded `azure-core` from `1.37.0` to version `1.38.0`. - -## 4.6.0 (2023-03-18) - -### Features Added -- Added support for service version `7.4`. - -### Breaking Changes -> These changes do not impact the API of stable versions such as `4.5.4`. Only code written against a beta version such as `4.6.0-beta.1` may be affected. -- Removed support for Octet Key Pair (OKP) operations. - -### Other Changes -- Upgraded `azure-core-http-netty` from `1.13.0` to version `1.13.1`. -- Upgraded `azure-core` from `1.36.0` to version `1.37.0`. - -## 4.5.4 (2023-02-16) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.12.8` to version `1.13.0`. -- Upgraded `azure-core` from `1.35.0` to version `1.36.0`. - -## 4.5.3 (2023-01-09) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.34.0` to version `1.35.0`. -- Upgraded `azure-core-http-netty` from `1.12.7` to version `1.12.8`. - -## 4.6.0-beta.1 (2022-11-11) - -### Features Added -- Added `CreateOkpKeyOptions` to pass key options when creating an Octet Key Pair (OKP) on Managed HSM. -- Added `createOkpKey()` and `createOkpKeyWithResponse()` to `KeyClient` and `KeyAsyncClient` to create an Octet Key Pair (OKP) on Managed HSM. -- Added `OKP` and `OKP_HSM` to `KeyType`. -- Added `Ed25519` to `KeyCurveName` to create an Octet Key Pair (OKP) using the Ed25519 curve. -- Added `EDDSA` to `SignatureAlgorithm` to support signing and verifying using an Edwards Curve Digital Signature Algorithm (EdDSA) on Managed HSM. -- Added support for service version `7.4-preview.1`. - -## 4.5.2 (2022-11-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.33.0` to version `1.34.0`. -- Upgraded `azure-core-http-netty` from `1.12.6` to version `1.12.7`. - -## 4.5.1 (2022-10-17) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.32.0` to version `1.33.0`. -- Upgraded `azure-core-http-netty` from `1.12.5` to version `1.12.6`. - -## 4.5.0 (2022-09-20) - -### Breaking Changes -- Made it so that we verify that the challenge resource matches the vault domain by default. This should affect few customers who can use the `disableChallengeResourceVerification()` method in client builders to disable this functionality. See https://aka.ms/azsdk/blog/vault-uri for more information. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.31.0` to version `1.32.0`. -- Upgraded `azure-core-http-netty` from `1.12.4` to version `1.12.5`. - -## 4.4.6 (2022-08-17) - -### Bugs Fixed -- Fixed an issue where requests sent by sync clients that should include a body could have an empty body instead. ([#30512](https://github.com/Azure/azure-sdk-for-java/pull/30512)) - -## 4.4.5 (2022-08-15) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.31.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.4`. - -## 4.4.4 (2022-07-06) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.30.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.3`. - -## 4.4.3 (2022-06-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.29.1`. -- Upgraded `azure-core-http-netty` dependency to `1.12.2`. - -## 4.4.2 (2022-05-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.28.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.0`. - -## 4.4.1 (2022-04-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.27.0`. -- Upgraded `azure-core-http-netty` dependency to `1.11.9`. - -## 4.4.0 (2022-03-31) - -### Features Added -- Added support for service version `7.3`. -- Added the following APIs to `KeyClient` and `KeyAsyncClient`: - - `getRandomBytes` and `getRandomBytesWithResponse` which, when connected to a managed HSM, can be used to generate a byte array of a given length with random values. - - `releaseKey` and `releaseKeyWithResponse` which support securely releasing a key from a Managed HSM. - - `rotateKey` and `rotateKeyWithResponse` which allow to rotate a key on-demand in Azure Key Vault and Managed HSM. - - `getKeyRotationPolicy` and `getKeyRotationPolicyWithResponse` which allow to retrieve a key's automated rotation policy. - - `updateKeyRotationPolicy` and `updateKeyRotationPolicyWithResponse` which allow to update a key's automated rotation policy. - - `getCryptographyClient` and `getCryptographyAsyncClient` which provide a simple way to create a `CryptographyClient` and `CryptographyAsyncClient` respectively for a key given its name and optionally a version. -- Additionally added the following classes to support the aforementioned APIs: - - `KeyRotationPolicy` which represents a key's automated rotation policy. - - `KeyRotationLifetimeAction` which represents an action that will be performed by Key Vault over the lifetime of a key. - - `KeyRotationPolicyAction`, an enum for the types of key rotation policy actions that can be executed relative to a key. - - `KeyReleasePolicy` which represents the policy rules under which the key can be exported. - - `ReleaseKeyOptions` which represents the configurable options to release a key. - - `KeyExportEncryptionAlgorithm`, an enum for specifying an encryption algorithm to be used during key release. - - `ReleaseKeyResult` which contains the value of a released key. -- `exportable` and `releasePolicy` were added to the following classes as well: - - `KeyProperties` - - `CreateKeyOptions` - - `CreateEcKeyOptions` - - `CreateOctKeyOptions` - - `CreateRsaKeyOptions` - - in order to specify whether the key is exportable and to associate a release policy to a given key -- `CryptographyClientBuilder` does not require `keyIdentifier` to a include a key version. If no version is provided, cryptographic operations will be made using the latest version of the key. -- Implemented new traits (micro-interfaces) in `KeyClientBuilder`, `CryptographyClientBuilder` and `KeyEncryptionKeyClientBuilder`. This makes the experience of using client builders more consistent across libraries in the Azure SDK for Java. - -### Breaking Changes -> These changes do not impact the API of stable versions such as `4.3.0`. -> Only code written against beta version `4.4.0-beta.7` may be affected. -- Changed `getRandomBytes` operations in `KeyClient` and `KeyAsyncClient` to return `byte[]` instead of `RandomBytes`. -- Removed the `RandomBytes` class. - -## 4.3.8 (2022-03-17) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.26.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.8` - -## 4.4.0-beta.7 (2022-02-11) - -### Features added -- Implemented new traits (micro-interfaces) in `KeyClientBuilder`, `CryptographyClientBuilder` and `KeyEncryptionKeyClientBuilder`. This makes the experience of using client builders more consistent across libraries in the Azure SDK for Java. -- Added the `immutable` property to `KeyReleasePolicy`. - -### Breaking Changes -- Removed the `exports` statement for `com.azure.security.keyvault.keys.implementation` in `module-info.java`. -- `KeyReleasePolicy` - - Renamed `data` to `encodedPolicy` and changed its type from `byte[]` to `BinaryData`. - - Flattened `KeyRotationPolicyProperties` into `KeyRotationPolicy`. - - Renamed `expiryTime` to `expiresIn`. -- Renamed `target` to `targetAttestationToken` in `releaseKey` APIs. -- Removed `KeyExportRequestParameters` as the `export` operations will be pushed to a future release. -- Renamed `KeyRotationLifetimeAction`'s `type` to `action`, to align with existing similar APIs in Key Vault Certificates. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.25.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.7` - -## 4.3.7 (2022-02-11) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.25.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.7` - -## 4.4.0-beta.6 (2022-01-13) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.24.1` -- Upgraded `azure-core-http-netty` dependency to `1.11.6` - -## 4.3.6 (2022-01-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.24.1` -- Upgraded `azure-core-http-netty` dependency to `1.11.6` - -## 4.4.0-beta.5 (2021-11-12) - -### Features Added - -- Added support for multi-tenant authentication in clients. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.22.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.2` - -## 4.3.5 (2021-11-12) - -### Features Added - -- Added support for multi-tenant authentication in clients. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.22.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.2` - -## 4.4.0-beta.4 (2021-10-07) - -### Features Added -- Added new functions to key clients to enable key rotation: - - `KeyClient` - - `rotateKey(String name)` - - `rotateKeyWithResponse(String name, Context context)` - - `getKeyRotationPolicy(String name)` - - `getKeyRotationPolicyWithResponse(String name, Context context)` - - `updateKeyRotationPolicy(String name, KeyRotationPolicyProperties keyRotationPolicyProperties)` - - `updateKeyRotationPolicyWithResponse(String name, KeyRotationPolicyProperties keyRotationPolicyProperties, Context context)` - - `KeyAsyncClient` - - `rotateKey(String name)` - - `rotateKeyWithResponse(String name)` - - `getKeyRotationPolicy(String name)` - - `getKeyRotationPolicyWithResponse(String name)` - - `updateKeyRotationPolicy(String name, KeyRotationPolicyProperties keyRotationPolicyProperties)` - - `updateKeyRotationPolicyWithResponse(String name, KeyRotationPolicyProperties keyRotationPolicyProperties)` -- Added convenience methods to create cryptography clients using key clients: - - `KeyClient.getCryptographyClient(String keyName)` - - `KeyClient.getCryptographyClient(String keyName, String keyVersion)` - - `KeyAsyncClient.getCryptographyAsyncClient(String keyName)` - - `KeyAsyncClient.getCryptographyAsyncClient(String keyName, String keyVersion)` -- `CryptographyClientBuilder` does not require `keyIdentifier` to a include a key version. If no version is provided, cryptographic operations will be made using the latest version of the key. - -### Bugs Fixed -- Fixed an issue that made clients send unnecessary unauthorized requests to obtain a bearer challenge from the service even when already possessing a valid bearer token. -- Fixed issue that prevented creating a `CryptographyClient` or `CryptographyAsyncClient` with a key identifier that does not contain a key version. -- Fixed issue that made `createOctKey()` operations ignore a `keySize` set in `CreateOctKeyOptions`, making said keys be created with the default service key size instead. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.21.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.1` - -## 4.3.4 (2021-10-06) - -### Bugs Fixed -- Fixed an issue that made clients send unnecessary unauthorized requests to obtain a bearer challenge from the service even when already possessing a valid bearer token. -- Fixed issue that prevented creating a `CryptographyClient` or `CryptographyAsyncClient` with a key identifier that does not contain a key version. -- Fixed issue that made `createOctKey()` operations ignore a `keySize` set in `CreateOctKeyOptions`, making said keys be created with the default service key size instead. - -## 4.4.0-beta.3 (2021-09-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.20.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.0` - -## 4.3.3 (2021-09-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.20.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.0` - -## 4.4.0-beta.2 (2021-08-13) - -### Features Added -- To support Secure Key Release for Key Vault and Managed HSM, added `Exportable` and `ReleasePolicy` to the following classes: - - `CreateKeyOptions` and its children classes: `CreateEcKeyOptions`, `CreateOctKeyOptions` and `CreateRsaKeyOptions`. - - `ImportKeyOptions` - - `KeyProperties` -- Added `releaseKey()` and `releaseKeyWithResponse()` operations to `KeyClient` and `KeyAsyncClient` to securely release a key for Key Vault and Managed HSM. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.19.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.2` - -## 4.3.2 (2021-08-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.19.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.2` - -## 4.4.0-beta.1 (2021-07-09) - -### Features Added -- Added support for service version `7.3-preview`. -- Added support for requesting a desired amount of randomly generated bytes from a Managed HSM. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.18.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.1` - -## 4.3.1 (2021-07-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.18.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.1` - -## 4.3.0 (2021-06-17) - -### Features Added -- Changed default service version to `7.2`. -- Added `KeyVaultKeyIdentifier` to parse key URLs. -- Added local-only support for `CryptographyClient` and `CryptographyAsyncClient` by providing a `JsonWebKey` during client creation. -- Added `KeyType.OCT-HSM` to support oct-HSM key operations to support Managed HSM. -- Added the `CreateOctKeyOptions` class and associated `createOctKey()` methods. -- Added AES-GCM and AES-CBC support for encrypting and decrypting, including new `Encrypt` and `Decrypt` overloads. -- Added the ability to set a public exponent on RSA keys during creation. -- Made all getters for properties of a `JsonWebKey` public. - -### Changes since 4.3.0-beta.8 - -#### Bug Fixes -- Ensured that `RetryPolicy` and `HttpLogOptions` use a default implementation when creating Key Vault clients if not set or set to `null`. - -#### New Features -- Added `createOctKey()` and `createOctKeyWithResponse()` to `KeyClient` and `KeyAsyncClient`. -- Added factory methods for RSA algorithms in `DecryptParameters` and `EncryptParameters`: - - `createRsa15Parameters()` - - `createRsaOaepParameters()` - - `createRsaOaep256Parameters()` - -#### Breaking Changes -- Removed `EXPORT` from the `KeyOperation` enum. -- Re-ordered parameters in the `EncryptResult` constructor to show `authenticationTag` before `additionalAuthenticatedData` to align with classes like `DecryptParameters`. -- Removed service method overloads that take a `pollingInterval`, since `PollerFlux` and `SyncPoller` objects allow for setting this value directly on them. -- Moved `EncryptParameters` and `DecryptParameters` from the `cryptography` package to the `cryptography.models` package and made them both `final`. - -#### Non-Breaking -- Renamed `keyId` to `sourceId` in `KeyVaultKeyIdentifier`. -- `KeyVaultKeyIdentifier` can now be used to parse any Key Vault identifier. -- Added the `@ServiceMethod` annotation to all public methods that call the Key Vault service in `KeyClient`, `KeyAsyncClient`, `CryptographyClient` and `CryptographyAsyncClient`. - -## 4.3.0-beta.8 (2021-05-15) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.16.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.2` -- Upgraded `azure-identity` dependency to `1.3.0` - -## 4.3.0-beta.7 (2021-04-29) - -### Bug fixes -- Fixed issue that prevented setting tags on keys when creating or importing them. - -### Breaking Changes -- Removed the `exportKey()` operation from `KeyAsyncClient` and `KeyClient`, as it is not yet supported in the current service version. - -## 4.3.0-beta.6 (2021-04-09) - -### Breaking Changes -- Renamed `EncryptOptions` to `EncryptParameters`. -- Renamed `DecryptOptions` to `DecryptParameters`. -- Changed `KeyVaultKeyIdentifier` so it is instantiated via its constructor as opposed to via a `parse()` factory method. -- Removed the following classes: - - `LocalCryptographyAsyncClient` - - `LocalCryptographyClient` - - `LocalCryptographyClientBuilder` - - `LocalKeyEncryptionKeyClient` - - `LocalKeyEncryptionKeyAsyncClient` - - `LocalKeyEncryptionKeyClientBuilder` - -### New features -- Added support for service version `7.2`. -- Made all `JsonWebKey` properties settable. -- Added support to specify whether or not a pipeline policy should be added per call or per retry. -- Added convenience class `CreateOctKeyOptions`. -- Added support for building local-only cryptography clients by providing a `JsonWebKey` for local operations: - - `CryptograhpyClientBuilder.jsonWebKey(JsonWebKey)` -- Added support for building local-only key encryption key clients by providing a `JsonWebKey` for local operations: - - `KeyEncryptionKeyClientBuilder.buildKeyEncryptionKey(JsonWebKey)` - - `KeyEncryptionKeyClientBuilder.buildAsyncKeyEncryptionKey(JsonWebKey)` -- `CryptograhpyClientBuilder.keyIdentifier(String)` now throws a `NullPointerException` if a `null` value is provided as an argument. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.15.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.1` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.1` -- Upgraded `azure-identity` dependency to `1.2.5` - -## 4.3.0-beta.5 (2021-03-12) - -### Breaking Changes -- Removed local support for encryption and decryption using AESGCM, as per guidance of Microsoft's cryptography board. Remote encryption and decryption using said algorithm is still supported. - -### Changed -- Changed logging level in `onRequest` and `onSuccess` calls for service operations from `INFO` to `VERBOSE`. - -### Bug fixes -- Fixed issue that caused a `NullPointerException` when attempting to use a `CryptographyClient` for symmetric key encryption operations after the first one. -- Fixed issue where `JsonWebKey` byte array contents would get serialized/deserialized using Base64 instead of URL-safe Base64. -- Fixed issue where properties of responses received when using a `CryptographyClient` for encryption/decryption were not populated on the `EncryptResult` and `DecryptResult` classes. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.14.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.0` -- Upgraded `azure-identity` dependency to `1.2.4` - -## 4.3.0-beta.4 (2021-02-11) - -### Bug Fixes -- Fixed issue where cryptographic operations would be attempted locally for symmetric keys that were missing their key material ('k' component). - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.13.0` -- Upgraded `azure-core-http-netty` dependency to `1.8.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.2.3` - -## 4.2.5 (2021-02-11) - -### Bug Fixes -- Fixed issue where cryptographic operations would be attempted locally for symmetric keys that were missing their key material ('k' component). - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.13.0` -- Upgraded `azure-core-http-netty` dependency to `1.8.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.2.3` - -## 4.2.4 (2021-01-15) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.12.0` -- Upgraded `azure-core-http-netty` dependency to `1.7.1` -- Upgraded `azure-core-http-okhttp` dependency to `1.4.1` -- Upgraded `azure-identity` dependency to `1.2.2` - -## 4.3.0-beta.3 (2020-11-19) - -### New Features -- Added support for encrypting and decrypting AES-GCM and AES-CBC keys. -- Added `KeyType.OCT_HSM` to support "oct-HSM" key operations. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.10.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.3` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.3` -- Upgraded `azure-core-test` dependency to `1.5.1` -- Upgraded `azure-identity` dependency to `1.2.0` - -## 4.2.3 (2020-11-12) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.10.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.3` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.3` -- Upgraded `azure-core-test` dependency to `1.5.1` -- Upgraded `azure-identity` dependency to `1.2.0` - -## 4.3.0-beta.2 (2020-10-09) - -### New Features -- Added `KeyVaultKeyIdentifier`. Use its [`parse`](https://github.com/Azure/azure-sdk-for-java/blob/ff52067a3772a430e5913b898f2806078aec8ef2/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifier.java#L78) method to parse the different elements of a given key identifier. -- Added API overloads that allow for passing specific polling intervals for long-running operations: - - `KeyAsyncClient` - - `beginDeleteKey(String, Duration)` - - `beginRecoverDeletedKey(String, Duration)` - - `KeyClient` - - `beginDeleteKey(String, Duration)` - - `beginRecoverDeletedKey(String, Duration)` -- Added support for `com.azure.core.util.ClientOptions` in client builders. - -### Bug Fixes -- Fixed an issue that prevented the `tags` and `managed` members of `KeyProperties` from getting populated when retrieving a single key using `KeyClient`, `KeyAsyncClient`, `CryptographyClient` and `CryptographyAsyncClient`. - -### Dependency updates -- Upgraded `azure-core` dependency to `1.9.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.2` -- Upgraded `azure-core-test` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.1.3` - -## 4.2.2 (2020-10-08) - -### Bug Fixes -- Fixed an issue that prevented the `tags` and `managed` members of `KeyProperties` from getting populated when retrieving a single key using `KeyClient`, `KeyAsyncClient`, `CryptographyClient` and `CryptographyAsyncClient`. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.9.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.2` -- Upgraded `azure-core-test` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.1.3` - -## 4.3.0-beta.1 (2020-09-11) -- Updated versions for azure-core and azure-identity. - -## 4.2.1 (2020-09-10) -- Updated versions for azure-core and azure-identity. - -## 4.2.0 (2020-08-12) -- Added support for service version `7.1`. -- Added `retryPolicy` setter in `KeyClientBuilder`, `CryptographyClientBuilder` and `KeyEncryptionKeyClientBuilder`. -- Added `recoverableDays` property to `KeyProperties`. -- Added `Import` operation to `KeyOperation`. - -## 4.2.0-beta.5 (2020-07-08) -- Updated versions for azure-core, azure-identity. - -## 4.1.5 (2020-07-08) -- Updated versions for azure-core and azure-identity. - -## 4.2.0-beta.4 (2020-06-10) -- Updated version for azure-core, azure-identity and external dependencies. -- `404` responses from `listPropertiesOfKeyVersions` in `KeyAsyncClient` and `KeyClient` now throw a `ResourceNotFoundException`. -- `buildAsyncKeyEncryptionKey` in `LocalKeyEncryptionKeyClientBuilder` now throws an exception when no ID is present in a given `JsonWebKey`. - -## 4.1.4 (2020-06-10) -- Updated version for azure-core, azure-identity and external dependencies. -- `404` responses from `listPropertiesOfKeyVersions` in `KeyAsyncClient` and `KeyClient` now throw a `ResourceNotFoundException`. - -## 4.1.3 (2020-05-06) -- Update azure-core dependency to version 1.5.0. - -## 4.2.0-beta.3 (2020-04-09) -- Added `LocalCryptographyClient`, `LocalCryptographyAsyncClient`, `LocalKeyEncryptionKeyClient` and `LocalKeyEncryptionKeyAsyncClient` to perform cryptography operations locally. -- Added `retryPolicy` setter in `KeyClientBuilder`, `CryptographyClientBuilder` and `KeyEncryptionKeyClientBuilder` -- Update azure-core dependency to version 1.4.0. - -## 4.1.2 (2020-04-07) -- Update azure-core dependency to version 1.4.0. - -## 4.1.1 (2020-03-25) -- Update azure-core dependency to version 1.3.0. - -## 4.2.0-beta.2 (2020-03-10) -### Added -- Added `recoverableDays` property to `KeyProperties`. -- Added `Import` operation to `KeyOperation`. -- Added support for `7.1-Preview` service version - -## 4.2.0-beta.1 -- `KeyVaultKey` model can be instantiated using `fromKeyId(String keyId, JsonWebKey jsonWebKey)` and `fromName(String name, JsonWebKey jsonWebKey)` methods on the `KeyVaultKey` model. -- Allows `KeyEncryptionKeyClientBuilder` to consume `KeyVaultKey` model and build `KeyEncryptionKey` and `AsyncKeyEncryptionKey` via`buildKeyEncryptionKey(KeyVaultKey key) ` and `buildAsyncKeyEncryptionKey(KeyVaultKey key)` methods respectively. - -## 4.1.0 (2020-01-07) -- Fixes the logic of `getKeyId()` method in `KeyEncryptionKeyClient` and `KeyEncryptionKeyAsyncClient` to ensure key id is available in all scenarios. -- Update azure-core dependency to version 1.2.0. - -## 4.0.1 (2019-12-06) - -### Major changes -- `KeyEncryptionKeyClientBuilder.buildKeyEncryptionKey` and `KeyEncryptionKeyClientBuilder.buildAsyncKeyEncryptionKey`supports consumption of a secret id representing the symmetric key stored in the Key Vault as a secret. -- Dropped third party dependency on apache commons codec library. - -### Breaking changes -- Key has been renamed to KeyVaultKey to avoid ambiguity with other libraries and to yield better search results. -- Key.keyMaterial has been renamed to KeyVaultKey.key. -- The setters of JsonWebKey properties have been removed. -- JsonWebKey methods fromRsa, fromEc and fromAes now take an optional collection of key operations. -- JsonWebKey.keyOps is now read-only. You must pass a list of key operations at construction time. -- endpoint method on KeyClientBuilder has been renamed to vaultUrl. -- hsm properties and parameters have been renamed to hardwareProtected. -- On KeyProperties, expires, created, and updated have been renamed to expiresOn, createdOn, and updatedOn respectively. -- On DeletedKey, deletedDate has been renamed to DeletedOn. -- listKeys and listKeyVersions methods have been renamed to listPropertiesOfKeys and listPropertiesOfKeyVersions respectively in `KeyClient` and `KeyAsyncClient`. -- restoreKey method has been renamed to restoreKeyBackup in `KeyClient` and `KeyAsyncClient` to better associate it with KeyClient.backupKey. -- deleteKey method has been renamed to beginDeleteKey and now returns a SyncPoller in `KeyClient` and PollerFlux in `KeyAsyncClient` to track this long-running operation. -- recoverDeletedKey method has been renamed to beginRecoverDeletedKey and now returns a SyncPoller in `KeyClient` and PollerFlux in `KeyAsyncClient` to track this long-running operation. -- KeyCreateOptions has been renamed to CreateKeyOptions. -- EcCreateKeyOptions has been renamed to CreateEcKeyOptions. -- CreateEcKeyOptions.curve has been renamed to curveName to be consistent. -- RsaKeyCreateOptions has been renamed to CreateRsaKeyOptions. -- KeyImportOptions has been renamed to ImportKeyOptions. - -### Major changes -- JsonWebKey.keyType and JsonWebKey.keyOps have been exposed as KeyVaultKey.keyType and KeyVaultKey.keyOperations respectively. -- KeyClient.vaultUrl has been added with the original value pass to KeyClient. - -## 4.0.0-preview.4 (2019-10-08) -For details on the Azure SDK for Java (September 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview4-java). - -- Updated to be fully compliant with the Java 9 Platform Module System. - -### Breaking changes -- `KeyBase` has been renamed to `KeyProperties`. -- `Key` and `DeletedKey` no longer extend `KeyProperties`, but instead contain a `KeyProperties` property named `Properties`. -- `updateKey` method has been renamed to `updateKeyProperties` in `KeyClient` and `KeyAsyncClient`. -- Getters and setters were updated to use Java Bean notation. -- Changed VoidResponse to Response on sync API, and Mono to Mono> on async API. -- Enumerations including `KeyCurveName`, `KeyOperation`, and `KeyType` are now structures that define well-known, supported static fields. - -## 4.0.0-preview.3 (2019-09-10) -For details on the Azure SDK for Java (August 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview3-java). - -## 4.0.0-preview.2 (2019-08-06) -For details on the Azure SDK for Java (August 2019 Preview) release refer to the [release announcement](https://azure.github.io/azure-sdk/releases/2019-08-06/index.html). - -- Added service side Cryptography Operations support for asymmetric keys (sign, un/wrap, verify, encrypt and decrypt) -- Added client side Cryptography Operations support both asymmetric and symmetric keys. -- Added Cryptography clients to `azure-keyvault-keys` package. - - `azure-keyvault-keys` contains a `CryptographyClient` and `CryptographyAsyncClient` for cryptography operations and `KeyClient` and `KeyAsyncClient` for key operations. - - see this package's - [documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-keyvault-keys_4.0.0-preview.2/sdk/keyvault/README.md) and - [samples](https://github.com/Azure/azure-sdk-for-java/tree/azure-keyvault-keys_4.0.0-preview.2/sdk/keyvault/azure-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys) for more information. -- Added support for HTTP challenge based authentication, allowing clients to interact with vaults in sovereign clouds. -- Combined KeyClientBuilder, KeyAsyncClientBuilder into KeyClientBuilder. Methods to create both sync and async clients type were added. -- Removed static builder method from clients. Builders are now instantiable. - -## 4.0.0-preview.1 (2019-06-28) -Version 4.0.0-preview.1 is a preview of our efforts in creating a client library that is developer-friendly, idiomatic to the Java ecosystem, and as consistent across different languages and platforms as possible. The principles that guide our efforts can be found in the [Azure SDK Design Guidelines for Java](https://aka.ms/azsdk/guide/java). - -For details on the Azure SDK for Java (July 2019 Preview) release, you can refer to the [release announcement](https://aka.ms/azure-sdk-preview1-java). - -This library is not a direct replacement for keys management operations from microsoft-azure-keyvault. Applications using that library would require code changes to use `azure-keyvault-keys`. -This package's -[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-keyvault-keys_4.0.0-preview.1/keyvault/client/keys/README.md) -and -[samples](https://github.com/Azure/azure-sdk-for-java/tree/azure-keyvault-keys_4.0.0-preview.1/keyvault/client/keys/src/samples/java) -demonstrate the new API. - -### Major changes from `azure-keyvault` -- Packages scoped by functionality - - `azure-keyvault-keys` contains a `KeyClient` and `KeyAsyncClient` for key operations, - `azure-keyvault-secrets` contains a `SecretClient` and `SecretAsyncClient` for secret operations -- Client instances are scoped to vaults (an instance interacts with one vault -only) -- Reactive streams support using [Project Reactor](https://projectreactor.io/). -- Authentication using `azure-identity` credentials - - see this package's - [documentation](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - , and the - [Azure Identity documentation](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity/README.md) - for more information - -### `azure-keyvault` features not implemented in this library -- Certificate management APIs -- Cryptographic operations, e.g. sign, un/wrap, verify, encrypt and decrypt -- National cloud support. This release supports public global cloud vaults, - e.g. https://{vault-name}.vault.azure.net diff --git a/sdk/keyvault/azure-security-keyvault-keys/README.md b/sdk/keyvault/azure-security-keyvault-keys/README.md deleted file mode 100644 index 7ad56e478159..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/README.md +++ /dev/null @@ -1,373 +0,0 @@ -# Azure Key Vault Key client library for Java -Azure Key Vault is a cloud service that provides secure storage of keys for encrypting your data. Multiple keys, and multiple versions of the same key, can be kept in the Azure Key Vault. Cryptographic keys in Azure Key Vault are represented as [JSON Web Key [JWK]][jwk_specification] objects. - -Azure Key Vault Managed HSM is a fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs. - -The Azure Key Vault keys library client supports RSA keys and Elliptic Curve (EC) keys, each with corresponding support in hardware security modules (HSM). It offers operations to create, retrieve, update, delete, purge, backup, restore, and list the keys and its versions. - -[Source code][source_code] | [API reference documentation][api_documentation] | [Product documentation][azkeyvault_docs] | [Samples][keys_samples] - -## Getting started -### Include the package -#### Include the BOM file -Please include the `azure-sdk-bom` to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. To learn more about the BOM, see the [AZURE SDK BOM README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/boms/azure-sdk-bom/README.md). - -```xml - - - - com.azure - azure-sdk-bom - {bom_version_to_target} - pom - import - - - -``` - -and then include the direct dependency in the dependencies section without the version tag as shown below. - -```xml - - - com.azure - azure-security-keyvault-keys - - -``` - -#### Include direct dependency -If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows. - -[//]: # ({x-version-update-start;com.azure:azure-security-keyvault-keys;current}) -```xml - - com.azure - azure-security-keyvault-keys - 4.9.2 - -``` -[//]: # ({x-version-update-end}) - -### Prerequisites -- A [Java Development Kit (JDK)][jdk_link], version 8 or later. - - Here are details about [Java 8 client compatibility with Azure Certificate Authority](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis). -- An [Azure Subscription][azure_subscription]. -- One of the following: - - An existing [Azure Key Vault][azure_keyvault]. If you need to create a key vault, you can do so in the Azure Portal by following the steps in [this document][azure_keyvault_portal]. Alternatively, you can use the Azure CLI by following the steps in [this document][azure_keyvault_cli]. - - An existing [Azure Key Vault Managed HSM][azure_keyvault_mhsm]. If you need to create a Managed HSM, you can do so using the Azure CLI by following the steps in [this document][azure_keyvault_mhsm_cli]. - -### Authenticate the client -In order to interact with the Azure Key Vault service, you will need to create an instance of either the [`KeyClient`](#create-key-client) class or the [`CryptographyClient`](#create-cryptography-client) class, as well as a **vault url** and a credential object. The examples shown in this document use a credential object named [`DefaultAzureCredential`][default_azure_credential], which is appropriate for most scenarios, including local development and production environments. Additionally, we recommend using a [managed identity][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][azure_identity]. - -#### Create key client -Once you perform [the authentication set up that suits you best][default_azure_credential] and replaced **your-key-vault-url** with the URL for your key vault or managed HSM, you can create the `KeyClient`: - -```java readme-sample-createKeyClient -KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); -``` - -> NOTE: For using an asynchronous client use `KeyAsyncClient` instead of `KeyClient` and call `buildAsyncClient()`. - -#### Create cryptography client -Once you perform [the `DefaultAzureCredential` set up that suits you best][default_azure_credential] and replaced **your-key-vault-url** with the URL for your key vault or managed HSM, you can create the `CryptographyClient`: - -```java readme-sample-createCryptographyClient -// Create client with key identifier from Key Vault. -CryptographyClient cryptoClient = new CryptographyClientBuilder() - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); -``` - -> NOTE: For using an asynchronous client use `CryptographyAsyncClient` instead of `CryptographyClient` and call `buildAsyncClient()`. - -## Key concepts -### Key -Azure Key Vault supports multiple key types (`RSA` & `EC`) and algorithms, and enables the use of Hardware Security Modules (HSM) for high value keys. In addition to the key material, the following attributes may be specified: -* enabled: Specifies whether the key is enabled and usable for cryptographic operations. -* not_before: Identifies the time before which the key must not be used for cryptographic operations. -* expires: Identifies the expiration time on or after which the key MUST NOT be used for cryptographic operations. -* created: Indicates when this version of the key was created. -* updated: Indicates when this version of the key was updated. - -### Key client: -The key client performs the interactions with the Azure Key Vault service for getting, setting, updating, deleting, and listing keys and its versions. Asynchronous (`KeyAsyncClient`) and synchronous (`KeyClient`) clients exist in the SDK allowing for the selection of a client based on an application's use case. Once you have initialized a key, you can interact with the primary resource types in Key Vault. - -### Cryptography client: -The cryptography client performs the cryptographic operations locally or calls the Azure Key Vault service depending on how much key information is available locally. It supports encrypting, decrypting, signing, verifying, key wrapping, key unwrapping, and retrieving the configured key. Asynchronous (`CryptographyAsyncClient`) and synchronous (`CryptographyClient`) clients exist in the SDK allowing for the selection of a client based on an application's use case. - -## Examples -### Sync API -The following sections provide several code snippets covering some of the most common Azure Key Vault Key service tasks, including: -- [Create a key](#create-a-key) -- [Retrieve a key](#retrieve-a-key) -- [Update an existing key](#update-an-existing-key) -- [Delete a key](#delete-a-key) -- [List keys](#list-keys) -- [Encrypt](#encrypt) -- [Decrypt](#decrypt) - -#### Create a key -Create a key to be stored in the Azure Key Vault. -- `createKey` creates a new key in the key vault. If a key with the same name already exists then a new version of the key is created. - -```java readme-sample-createKey -KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)); -System.out.printf("Key created with name \"%s\" and id %s%n", rsaKey.getName(), rsaKey.getId()); - -KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setCurveName(KeyCurveName.P_256) - .setExpiresOn(OffsetDateTime.now().plusYears(1))); -System.out.printf("Key created with name \"%s\" and id %s%n", ecKey.getName(), ecKey.getId()); -``` - -#### Retrieve a key -Retrieve a previously stored key by calling `getKey`. - -```java readme-sample-retrieveKey -KeyVaultKey key = keyClient.getKey(""); -System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName(), key.getId()); -``` - -#### Update an existing key -Update an existing key by calling `updateKeyProperties`. - -```java readme-sample-updateKey -// Get the key to update. -KeyVaultKey key = keyClient.getKey(""); -// Update the expiry time of the key. -key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); -KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties()); -System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn()); -``` - -#### Delete a key -Delete an existing key by calling `beginDeleteKey`. - -```java readme-sample-deleteKey -SyncPoller deletedKeyPoller = keyClient.beginDeleteKey(""); - -PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); - -// Deleted key is accessible as soon as polling begins. -DeletedKey deletedKey = deletedKeyPollResponse.getValue(); -// Deletion date only works for a soft-delete enabled key vault. -System.out.printf("Deletion date: %s%n", deletedKey.getDeletedOn()); - -// The key is being deleted on the server. -deletedKeyPoller.waitForCompletion(); -``` - -#### List keys -List the keys in the key vault by calling `listPropertiesOfKeys`. - -```java readme-sample-listKeys -// List operations don't return the keys with key material information. So, for each returned key we call getKey to -// get the key with its key material information. -for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { - KeyVaultKey keyWithMaterial = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); - System.out.printf("Received key with name \"%s\" and type \"%s\"%n", keyWithMaterial.getName(), - keyWithMaterial.getKey().getKeyType()); -} -``` - -#### Encrypt -Encrypt plain text by calling `encrypt`. - -```java readme-sample-encrypt -byte[] plaintext = new byte[100]; -new SecureRandom(SEED).nextBytes(plaintext); - -// Let's encrypt a simple plain text of size 100 bytes. -EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); -System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); -``` - -#### Decrypt -Decrypt encrypted content by calling `decrypt`. - -```java readme-sample-decrypt -byte[] plaintext = new byte[100]; -new SecureRandom(SEED).nextBytes(plaintext); -EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); - -//Let's decrypt the encrypted result. -DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); -System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length); -``` - -### Async API -The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Key service tasks, including: -- [Create a key asynchronously](#create-a-key-asynchronously) -- [Retrieve a key asynchronously](#retrieve-a-key-asynchronously) -- [Update an existing key asynchronously](#update-an-existing-key-asynchronously) -- [Delete a key asynchronously](#delete-a-key-asynchronously) -- [List keys asynchronously](#list-keys-asynchronously) -- [Encrypt asynchronously](#encrypt-asynchronously) -- [Decrypt asynchronously](#decrypt-asynchronously) - -> Note : You should add `System.in.read()` or `Thread.sleep()` after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits. - -#### Create a key asynchronously -Create a key to be stored in the Azure Key Vault. -- `createKey` creates a new key in the key vault. If a key with the same name already exists then a new version of the key is created. - -```java readme-sample-createKeyAsync -keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)) - .subscribe(key -> - System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); - -keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(key -> - System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); -``` - -#### Retrieve a key asynchronously -Retrieve a previously stored key by calling `getKey`. - -```java readme-sample-retrieveKeyAsync -keyAsyncClient.getKey("") - .subscribe(key -> - System.out.printf("Key was returned with name \"%s\" and id %s%n", key.getName(), key.getId())); -``` - -#### Update an existing key asynchronously -Update an existing key by calling `updateKeyProperties`. - -```java readme-sample-updateKeyAsync -keyAsyncClient.getKey("") - .flatMap(key -> { - // Update the expiry time of the key. - key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); - return keyAsyncClient.updateKeyProperties(key.getProperties()); - }).subscribe(updatedKey -> - System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); -``` - -#### Delete a key asynchronously -Delete an existing key by calling `beginDeleteKey`. - -```java readme-sample-deleteKeyAsync -keyAsyncClient.beginDeleteKey("") - .subscribe(pollResponse -> { - System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); - System.out.printf("Deleted key name: %s%n", pollResponse.getValue().getName()); - System.out.printf("Key deletion date: %s%n", pollResponse.getValue().getDeletedOn()); - }); -``` - -#### List keys asynchronously -List the keys in the Azure Key Vault by calling `listPropertiesOfKeys`. - -```java readme-sample-listKeysAsync -// The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its value -// as well. -keyAsyncClient.listPropertiesOfKeys() - .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) - .subscribe(key -> - System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType())); -``` - -#### Encrypt asynchronously -Encrypt plain text by calling `encrypt`. - -```java readme-sample-encryptAsync -byte[] plaintext = new byte[100]; -new SecureRandom(SEED).nextBytes(plaintext); - -// Let's encrypt a simple plain text of size 100 bytes. -cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .subscribe(encryptionResult -> System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm())); -``` - -#### Decrypt asynchronously -Decrypt encrypted content by calling `decrypt`. - -```java readme-sample-decryptAsync -byte[] plaintext = new byte[100]; -new SecureRandom(SEED).nextBytes(plaintext); - -// Let's encrypt a simple plain text of size 100 bytes. -cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .flatMap(encryptionResult -> { - System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); - //Let's decrypt the encrypted response. - return cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); - }).subscribe(decryptionResult -> - System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); -``` - -## Troubleshooting -See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/TROUBLESHOOTING.md) for details on how to diagnose various failure scenarios. - -### General -Azure Key Vault Key clients raise exceptions. For example, if you try to retrieve a key after it is deleted a `404` error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. - -```java readme-sample-troubleshooting -try { - keyClient.getKey(""); -} catch (ResourceNotFoundException e) { - System.out.println(e.getMessage()); -} -``` - -### Default HTTP client -All client libraries by default use the Netty HTTP client. Adding the above dependency will automatically configure the client library to use the Netty HTTP client. Configuring or changing the HTTP client is detailed in the [HTTP clients wiki][http_clients_wiki]. - -### Default SSL library -All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an Uber JAR containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the [performance tuning][performance_tuning] section of the wiki. - -## Next steps -Several Azure Key Vault Java client library samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Azure Key Vault. - -## Next steps samples -Samples are explained in detail [here][samples_readme]. - -### Additional documentation -For more extensive documentation on Azure Key Vault, see the [API reference documentation][azkeyvault_rest]. - -## Contributing -This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. - -This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_code_of_conduct]. For more information see the Code of Conduct FAQ or contact with any additional questions or comments. - - -[source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src -[api_documentation]: https://azure.github.io/azure-sdk-for-java -[azkeyvault_docs]: https://learn.microsoft.com/azure/key-vault/ -[azure_identity]: https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable -[azure_subscription]: https://azure.microsoft.com/ -[azure_keyvault]: https://learn.microsoft.com/azure/key-vault/keys/quick-create-portal -[azure_keyvault_cli]: https://learn.microsoft.com/azure/key-vault/general/quick-create-cli -[azure_keyvault_portal]: https://learn.microsoft.com/azure/key-vault/general/quick-create-portal -[azure_keyvault_mhsm]: https://learn.microsoft.com/azure/key-vault/managed-hsm/overview -[azure_keyvault_mhsm_cli]: https://learn.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli -[default_azure_credential]: https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#defaultazurecredential -[managed_identity]: https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview -[azkeyvault_rest]: https://learn.microsoft.com/rest/api/keyvault/ -[keys_samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys -[samples_readme]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md -[performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -[jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable -[jwk_specification]: https://tools.ietf.org/html/rfc7517 -[http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients -[microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-keys%2FREADME.png) diff --git a/sdk/keyvault/azure-security-keyvault-keys/TROUBLESHOOTING.md b/sdk/keyvault/azure-security-keyvault-keys/TROUBLESHOOTING.md deleted file mode 100644 index 64760e0e7ae3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/TROUBLESHOOTING.md +++ /dev/null @@ -1,2 +0,0 @@ -# Troubleshooting Azure Key Vault Keys SDK Issues -See our general [Azure Key Vault SDK Troubleshooting Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/TROUBLESHOOTING.md) to troubleshoot issues common to the Azure Key Vault SDKs for Java. diff --git a/sdk/keyvault/azure-security-keyvault-keys/assets.json b/sdk/keyvault/azure-security-keyvault-keys/assets.json deleted file mode 100644 index 31f6f88f48d3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "java", - "TagPrefix": "java/keyvault/azure-security-keyvault-keys", - "Tag": "java/keyvault/azure-security-keyvault-keys_d9bef0f806" -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml deleted file mode 100644 index 7366f6709444..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk/keyvault/azure-security-keyvault-keys/migration_guide.md b/sdk/keyvault/azure-security-keyvault-keys/migration_guide.md deleted file mode 100644 index b99ec33f0044..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/migration_guide.md +++ /dev/null @@ -1,303 +0,0 @@ -# Guide for migrating to azure-security-keyvault-keys from azure-keyvault -This guide is intended to assist in the migration to `azure-security-keyvault-keys` from [deprecated] `azure-keyvault`. It will focus on side-by-side comparisons for similar operations between the two packages. - -Familiarity with the `azure-keyvault` package is assumed. For those new to the Key Vault Key client library for Java, please refer to the [README for azure-security-keyvault-keys](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) rather than this guide. - -## Table of contents -- [Migration benefits](#migration-benefits) -- [Cross Service SDK improvements](#cross-service-sdk-improvements) -- [Important changes](#important-changes) - - [Separate packages and clients](#separate-packages-and-clients) - - [Package names and namespaces](#package-names-and-namespaces) - - [Client instantiation](#client-instantiation) - - [Authentication](#authentication) - - [Common scenarios](#common-scenarios) - - [Async operations](#async-operations) - - [Create a key](#create-a-key) - - [Import a key](#import-a-key) - - [Retrieve a key](#retrieve-a-key) - - [List properties of keys](#list-properties-of-keys) - - [Delete a key](#delete-a-key) - - [Perform cryptographic operations](#perform-cryptographic-operations) -- [Additional samples](#additional-samples) -- [Support](#support) - -## Migration benefits -> Note: `azure-keyvault` has been [deprecated]. Please upgrade to `azure-security-keyvault-keys` for continued support. - -A natural question to ask when considering whether or not to adopt a new version or library is what the benefits of doing so would be. As Azure has matured and been embraced by a more diverse group of developers, we have been focused on learning the patterns and practices to best support developer productivity and to understand the gaps that the Java client libraries have. - -There were several areas of consistent feedback expressed across the Azure client library ecosystem. One of the most important is that the client libraries for different Azure services have not had a consistent approach to organization, naming, and API structure. Additionally, many developers have felt that the learning curve was difficult, and the APIs did not offer a good, approachable, and consistent onboarding story for those learning Azure or exploring a specific Azure service. - -To try and improve the development experience across Azure services, a set of uniform [design guidelines](https://azure.github.io/azure-sdk/general_introduction.html) was created for all languages to drive a consistent experience with established API patterns for all services. A set of [Java-specific guidelines](https://azure.github.io/azure-sdk/java_introduction.html) was also introduced to ensure that Java clients have a natural and idiomatic feel with respect to the Java ecosystem. Further details are available in the guidelines for those interested. - -### Cross Service SDK improvements -The modern Key Vault Key client library also provides the ability to share in some of the cross-service improvements made to the Azure development experience, such as: - -- Using the new Azure Identity library to share a single authentication approach between clients. -- A unified logging and diagnostics pipeline offering a common view of the activities across each of the client libraries. - -## Important changes -### Separate packages and clients -In the interest of simplifying the API for working with Key Vault certificates, keys and secrets, the `azure-keyvault` was split into separate packages: - -- [`azure-security-keyvault-certificates`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) contains `CertificateClient` for working with Key Vault certificates. -- `azure-security-keyvault-keys` contains `KeyClient` for working with Key Vault keys and `CryptographyClient` for performing cryptographic operations. -- [`azure-security-keyvault-secrets`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) contains `SecretClient` for working with Key Vault secrets. - -### Package names and namespaces -Package names and the namespace root for the modern Azure client libraries for Java have changed. Each will follow the pattern `com.azure..` where the legacy clients followed the pattern `com.microsoft.azure.`. This provides a quick and accessible means to help understand, at a glance, whether you are using the modern or legacy clients. - -In the case of the Key Vault, the modern client libraries have packages and namespaces that begin with `com.azure.security.keyvault` and were released beginning with version `4.0.0`. The legacy client libraries have packages and namespaces that begin with `com.microsoft.azure.keyvault` and a version of `1.x.x` or below. - -### Client instantiation -Previously in `azure-keyvault` you could create a `KeyVaultClient`, via a public constructor that took an authentication delegate and could be used for multiple Key Vault endpoints. - -```java -import com.microsoft.azure.keyvault.KeyVaultClient; -import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials; - -KeyVaultCredentials keyVaultCredentials = new MyKeyVaultCredentials("", ""); -KeyVaultClient keyVaultClient = new KeyVaultClient(keyVaultCredentials); -``` - -Now, across all modern Azure client libraries, client instances are created via builders, which consistently take an endpoint or connection string along with token credentials. This means that you can use a single client builder to instantiate multiple clients that share some configuration. - -```java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyClientBuilder; - -TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); -KeyClientBuilder keyClientBuilder = new KeyClientBuilder() - .vaultUrl("") - .credential(tokenCredential); - -// Create a client. -KeyClient someKeyClient = keyClientBuilder.buildClient(); - -// Create a client with the same configuration, plus some more. -KeyClient anotherKeyClient = keyClientBuilder - .addPolicy(new AddDatePolicy()) - .buildClient(); -``` - -### Authentication -Previously in `azure-keyvault` you could create a `KeyVaultClient` by passing either a `KeyVaultCredential` or `RestClient` from `client-runtime`: - -```java -import com.microsoft.azure.keyvault.KeyVaultClient; -import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials; - -KeyVaultCredentials keyVaultCredentials = new MyKeyVaultCredentials("", ""); -KeyVaultClient keyVaultClient = new KeyVaultClient(keyVaultCredentials); -``` - -Now in `azure-security-keyvault-keys` you can create a `KeyClient` using any credential from [`azure-identity`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md). Below is an example using [`DefaultAzureCredential`](https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#defaultazurecredential): - -```java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyClientBuilder; - -TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); - -KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(tokenCredential) - .buildClient(); -``` - -### Async operations -The modern `azure-security-keyvault-keys` library includes a complete set of async APIs that return [Project Reactor-based types](https://projectreactor.io/), as opposed to `azure-keyvault` async APIs that return either [Observable](https://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html) or [ServiceFuture](https://azure.github.io/ref-docs/java/com/microsoft/rest/ServiceFuture.html). - -Another difference is that async operations are available on their own separate async clients, which include the word `Async` in their name, like `KeyAsyncClient`. - -All modern Azure async clients can be created virtually the same way as sync clients, with the slight difference of calling `buildAsyncClient` on the client builder instead of `buildClient`: - -```java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyClientBuilder; - -TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); -KeyClientBuilder keyClientBuilder = new KeyClientBuilder() - .vaultUrl("") - .credential(tokenCredential); - -// To create an async client. -KeyAsyncClient keyAsyncClient = keyClientBuilder.buildAsyncClient(); - -// To create a sync client. -KeyClient keyClient = keyClientBuilder.buildClient(); -``` - -### Common scenarios -#### Create a key -In `azure-keyvault` you could create a key by using `KeyVaultClient`'s `createKey` method, which required a vault endpoint, key name, and key type. This method returned a `KeyBundle` containing the key. - -```java -String keyVaultUrl = "https://.vault.azure.net/"; - -// Create an RSA key. -KeyBundle rsaKey = keyVaultClient.createKey(keyVaultUrl, "", JsonWebKeyType.RSA); - -// Create an EC key. -KeyBundle ecKey = keyVaultClient.createKey(keyVaultUrl, "", JsonWebKeyType.EC); -``` - -Now in `azure-security-keyvault-keys` there are multiple ways to create keys: you can provide either a key name and type or creation options to the `createKey` method, or provide creation options to `createRsaKey` or `createEcKey`. These methods all return the created key as a `KeyVaultKey`. - -```java -// Create a key specifying the key type. -KeyVaultKey octKey = keyClient.createKey("", KeyType.OCT); - -// Create a key with creation options. -KeyVaultKey octKeyWithOptions = keyClient.createKey(new CreateKeyOptions("", KeyType.OCT) - .setExpiresOn(OffsetDateTime.now().plusYears(1))); - -// Create an RSA key. -KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("") - .setKeySize(2048)); - -// Create an EC key. -KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("") - .setCurveName(KeyCurveName.P_256K)); -``` - -#### Import a key -In `azure-keyvault` you could import a key by using `KeyVaultClient`'s `importKey` method, which required a vault endpoint, key name, and key contents as a `JsonWebKey`. This method returned a `KeyBundle`. - -```java -KeyBundle importedKey = keyVaultClient.importKey(keyVaultUrl, "", jsonWebKey); -``` - -Now in `azure-security-keyvault-keys` you can still import a key by providing the key name and contents as a `JsonWebKey` to `importKey`, but you can also do so by providing an options object. This method returns a `KeyVaultKey`. - -```java -// Import key using name and contents. -KeyVaultKey importedKey = keyClient.importKey(new ImportKeyOptions("", jsonWebKey)); - -// Import key using options. -KeyVaultKey anotherImportedKey = keyClient.importKey(new ImportKeyOptions("", keyContents) - .setExpiresOn(OffsetDateTime.now().plusYears(1))); -``` - -#### Retrieve a key -In `azure-keyvault` you could retrieve a key (in a `KeyBundle`) by using `getKey` in one of the following ways: - -- Using the desired key vault endpoint and key name to get the latest version of a key. -- Using the desired key vault endpoint, key name and key version to get a specific key version. -- Using the key identifier to get a specific key version. - -Additionally, you could list the properties of the versions of a key with the `getKeyVersions` method, which returned a `PagedList` of `KeyItem`. - -```java -String keyVaultUrl = "https://.vault.azure.net/"; - -// Get a key's latest version. -KeyBundle key = keyVaultClient.getKey(keyVaultUrl, ""); - -// Get a key's specific version. -KeyBundle keyVersion = keyVaultClient.getKey(keyVaultUrl, "", ""); - -// Get a key's specific version using its id. -String keyIdentifier = "https://.vault.azure.net/keys//"; -KeyBundle keyWithId = keyVaultClient.getKey(keyIdentifier); - -// Get a key's versions. -PagedList keyVersions = keyVaultClient.getKeyVersions(keyVaultUrl, ""); -``` - -Now in `azure-security-keyvault-keys` you can retrieve a key (as a `KeyVaultKey`) by using `getKey` in one of the following ways: - -- Using the key name to get the latest version of the key. -- Using the key name and key version to get a specific version of the key. - -Additionally, you con list the properties of the versions of a key with the `getKeyVersions` method, which returned a `PagedIterable` of `KeyProperties`. - -```java -// Get a key's latest version. -KeyVaultKey key = keyClient.getKey(""); - -// Get a key's specific version. -KeyVaultKey keyVersion = keyClient.getKey("", ""); - -// Get a key's versions' propeties. -PagedIterable keyVersionsProperties = keyClient.listPropertiesOfKeyVersions(""); -``` - -#### List properties of keys -In `azure-keyvault` you could list the properties of keys in a specified vault with the `getKeys` methods. This returned a `PagedList` containing `KeyItem` instances. - -```java -PagedList keysProperties = keyVaultClient.getKeys(keyVaultUrl); -``` - -Now in `azure-security-keyvault-keys` you can list the properties of keys in a vault with the `listPropertiesOfKeys` method. This returns an iterator-like object containing `KeyProperties` instances. - -```java -PagedIterable keysProperties = keyClient.listPropertiesOfKeys(); -``` - -#### Delete a key -In `azure-keyvault` you could delete all versions of a key with the `deleteKey` method. This returned information about the deleted key (as a `DeletedKeyBundle`), but you could not poll the deletion operation to know when it completed. This would be valuable information if you intended to permanently delete the deleted key with `purgeDeletedKey`. - -```java -DeletedKeyBundle deletedKey = keyVaultClient.deleteKey(keyVaultUrl, ""); - -// This purge would fail if deletion hadn't finished -keyVaultClient.purgeDeletedKey(keyVaultUrl, ""); -``` - -Now in `azure-security-keyvault-keys` you can delete a key with `beginDeleteKey`, which returns a long operation poller object that can be used to wait/check on the operation. Calling `poll` on the poller will return information about the deleted key (as a `DeletedKey`) without waiting for the operation to complete, but calling `waitForCompletion` will wait for the deletion to complete. Again, `purgeDeletedKey` will permanently delete your deleted key and make it unrecoverable. - -```java -SyncPoller deleteKeyPoller = keyClient.beginDeleteKey(""); -PollResponse deletePollResponse = deleteKeyPoller.poll(); -DeletedKey deletedKey = deletePollResponse.getValue(); - -// Wait for completion before attempting to purge the key. -deleteKeyPoller.waitForCompletion(); -keyClient.purgeDeletedKey(""); -``` - -#### Perform cryptographic operations -In `azure-keyvault` you could perform cryptographic operations with keys by using the `encrypt`/`decrypt`, `wrapKey`/`unwrapKey`, and `sign`/`verify` methods. Each of these methods accepted a key vault endpoint, key name, key version, and algorithm along with other parameters. - -```java -// Encrypt data using a key. -byte[] plaintext = "plaintext".getBytes(); -KeyOperationResult keyOperationResult = keyVaultClient.encrypt(keyVaultUrl, "", "", - JsonWebKeyEncryptionAlgorithm.RSA_OAEP_256, plaintext); -byte[] ciphertext = keyOperationResult.result(); -``` - -Now in `azure-security-keyvault-keys` you can perform these cryptographic operations by using a `CryptographyClient`. The key used to create the client will be used for these operations. Cryptographic operations are now performed locally by the client when it's initialized with the necessary key material or is able to get that material from Key Vault, and are only performed by the Key Vault service when required key material is unavailable. - -```java -String keyIdentifier = "https://.vault.azure.net/keys//"; -TokenCredentials tokenCredentials = new DefaultAzureCredentialBuilder().build(); - -CryptographyClient cryptographyClient = new CryptographyClientBuilder() - .keyIdentifier(keyIdentifier) - .credential(tokenCredentials) - .buildClient(); - -byte[] plaintext = "plaintext".getBytes(); -EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP_256, plaintext); -byte[] ciphertext = encryptResult.getCipherText(); -``` - -## Additional samples -More examples can be found [here](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/keyvault/azure-security-keyvault-keys/src/samples). - -## Support - -If you have migrated your code base and experiencing errors, see our [troubleshooting guide][troubleshooting_guide]. For additional support, please search our [existing issues][existing_issues] or [open a new issue][open_new_issue]. You may also find existing answers on community sites like [Stack Overflow]. - -[deprecated]: https://aka.ms/azsdk/deprecated -[existing_issues]: https://github.com/Azure/azure-sdk-for-java/issues -[open_new_issue]: https://github.com/Azure/azure-sdk-for-java/issues/new/choose -[stack_overflow]: https://stackoverflow.com/questions/tagged/azure-keyvault+java -[troubleshooting_guide]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/TROUBLESHOOTING.md diff --git a/sdk/keyvault/azure-security-keyvault-keys/pom.xml b/sdk/keyvault/azure-security-keyvault-keys/pom.xml deleted file mode 100644 index fcbca46a4935..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - com.azure - azure-client-sdk-parent - 1.7.0 - ../../parents/azure-client-sdk-parent - - - 4.0.0 - - com.azure - azure-security-keyvault-keys - 4.10.0-beta.1 - - Microsoft Azure client library for KeyVault Keys - This module contains client library for Microsoft Azure KeyVault Keys. - https://github.com/Azure/azure-sdk-for-java - - - - azure-java-build-docs - ${site.url}/site/${project.artifactId} - - - - - scm:git:https://github.com/Azure/azure-sdk-for-java - scm:git:git@github.com:Azure/azure-sdk-for-java.git - HEAD - - - - - - --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED - --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - - --add-opens com.azure.security.keyvault.keys/com.azure.security.keyvault.keys=ALL-UNNAMED - --add-opens com.azure.security.keyvault.keys/com.azure.security.keyvault.keys.cryptography=ALL-UNNAMED - --add-opens com.azure.security.keyvault.keys/com.azure.security.keyvault.keys.implementation=ALL-UNNAMED - --add-opens com.azure.security.keyvault.keys/com.azure.security.keyvault.keys.models=ALL-UNNAMED - - - checkstyle-suppressions.xml - false - spotbugs-exclude.xml - - - - - com.azure - azure-core - 1.54.1 - - - - com.azure - azure-json - 1.3.0 - - - - com.azure - azure-core-http-netty - 1.15.7 - - - - - com.azure - azure-core-test - 1.27.0-beta.4 - test - - - com.azure - azure-identity - 1.15.0 - test - - - diff --git a/sdk/keyvault/azure-security-keyvault-keys/spotbugs-exclude.xml b/sdk/keyvault/azure-security-keyvault-keys/spotbugs-exclude.xml deleted file mode 100644 index a45e771ee376..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/spotbugs-exclude.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java deleted file mode 100644 index b5024f510285..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java +++ /dev/null @@ -1,2077 +0,0 @@ -// 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; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java deleted file mode 100644 index 14c7f6e48fb1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java +++ /dev/null @@ -1,2107 +0,0 @@ -// 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.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -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.PollingContext; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.keys.cryptography.CryptographyClient; -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.BackupKeyResult; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyBundle; -import com.azure.security.keyvault.keys.implementation.models.KeyBundle; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.keys.implementation.models.RandomBytes; -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 java.net.HttpURLConnection; -import java.time.Duration; -import java.util.Arrays; -import java.util.function.Function; - -import static com.azure.security.keyvault.keys.KeyAsyncClient.mapDeletedKeyItemPagedResponse; -import static com.azure.security.keyvault.keys.KeyAsyncClient.mapKeyItemPagedResponse; -import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.callWithMappedException; -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 KeyClient} provides synchronous 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 Azure Key Vault. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link 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 {@link KeyClient}, using the {@link KeyClientBuilder} - * to configure it.

- * - * - *
- * KeyClient keyClient = new KeyClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *
- * - *
- * - *

Create a Cryptographic Key

- * The {@link KeyClient} 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 {@link KeyClient#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 {@link KeyAsyncClient}.

- * - *
- * - *
- * - *

Get a Cryptographic Key

- * The {@link KeyClient} 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 {@link KeyClient#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 {@link KeyAsyncClient}.

- * - *
- * - *
- * - *

Delete a Cryptographic Key

- * The {@link KeyClient} 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 {@link KeyClient#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 {@link KeyAsyncClient}.

- * - * @see com.azure.security.keyvault.keys - * @see KeyClientBuilder - */ -@ServiceClient(builder = KeyClientBuilder.class, serviceInterfaces = KeyClientImpl.KeyClientService.class) -public final class KeyClient { - private static final ClientLogger LOGGER = new ClientLogger(KeyClient.class); - - private final KeyClientImpl implClient; - private final String vaultUrl; - private final KeyServiceVersion serviceVersion; - - /** - * Creates a {@link KeyClient} that uses a {@link KeyClientImpl} to service requests. - * - * @param implClient the impl client. - * @param vaultUrl the vault url. - * @param serviceVersion the service version. - */ - KeyClient(KeyClientImpl implClient, String vaultUrl, KeyServiceVersion serviceVersion) { - this.implClient = implClient; - this.vaultUrl = vaultUrl; - this.serviceVersion = serviceVersion; - } - - /** - * Get the vault endpoint url to which service requests are sent to. - * - * @return The vault endpoint url. - */ - public String getVaultUrl() { - return vaultUrl; - } - - HttpPipeline getHttpPipeline() { - return implClient.getHttpPipeline(); - } - - /** - * Creates a {@link CryptographyClient} 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 CryptographyClient} 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 KeyClient#getCryptographyClient(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 CryptographyClient} associated with the latest version of a key with the - * provided name. - * - * @throws IllegalArgumentException If {@code keyName} is {@code null} or empty. - */ - public CryptographyClient getCryptographyClient(String keyName) { - return getCryptographyClient(keyName, null); - } - - /** - * Creates a {@link CryptographyClient} for a given key version. - * - * @param keyName The name of the key. - * @param keyVersion The key version. - * - * @return An instance of {@link CryptographyClient} 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 CryptographyClient getCryptographyClient(String keyName, String keyVersion) { - return KeyVaultKeysUtils - .getCryptographyClientBuilder(keyName, keyVersion, vaultUrl, getHttpPipeline(), serviceVersion) - .buildClient(); - } - - /** - * 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}. Prints out the details of the {@link KeyVaultKey created key}.

- * - *
-     * KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC);
-     * 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 The {@link KeyVaultKey created key}. - * - * @throws ResourceModifiedException If {@code name} or {@code keyType} are {@code null}. - * @throws HttpResponseException If {@code name} is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey createKey(String name, KeyType keyType) { - return createKeyWithResponse(new CreateKeyOptions(name, keyType), Context.NONE).getValue(); - } - - /** - * 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. Prints out the - * details of the {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the - * {@link KeyVaultKey key} being created. - * - * @return The {@link KeyVaultKey created key}. - * - * @throws HttpResponseException If {@link CreateKeyOptions#getName()} is an empty string. - * @throws NullPointerException If {@code createKeyOptions} is {@code null}. - * @throws HttpResponseException If {@code name} is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey createKey(CreateKeyOptions createKeyOptions) { - return createKeyWithResponse(createKeyOptions, Context.NONE).getValue(); - } - - /** - * 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. Prints out the - * details of the {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the - * {@link KeyVaultKey key} being created. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 {@code null}. - * @throws ResourceModifiedException If {@code createKeyOptions} is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { - if (createKeyOptions == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'createKeyOptions' cannot be null.")); - } - - Response response = callWithMappedException( - () -> implClient.createKeyWithResponse(vaultUrl, createKeyOptions.getName(), createKeyOptions.getKeyType(), - null, null, createKeyOptions.getKeyOperations(), createKeyAttributes(createKeyOptions), - createKeyOptions.getTags(), null, mapKeyReleasePolicy(createKeyOptions.getReleasePolicy()), context), - KeyAsyncClient::mapCreateKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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. - * Prints out the details of the {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the - * {@link KeyVaultKey RSA key} being created. - * - * @return 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 KeyVaultKey createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { - return createRsaKeyWithResponse(createRsaKeyOptions, Context.NONE).getValue(); - } - - /** - * 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. - * Prints out the details of the {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the - * {@link KeyVaultKey RSA key} being created. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 Response createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { - if (createRsaKeyOptions == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'createRsaKeyOptions' cannot be null.")); - } - - Response response = callWithMappedException( - () -> implClient.createKeyWithResponse(vaultUrl, createRsaKeyOptions.getName(), - createRsaKeyOptions.getKeyType(), createRsaKeyOptions.getKeySize(), - createRsaKeyOptions.getPublicExponent(), createRsaKeyOptions.getKeyOperations(), - createKeyAttributes(createRsaKeyOptions), createRsaKeyOptions.getTags(), null, - mapKeyReleasePolicy(createRsaKeyOptions.getReleasePolicy()), context), - KeyAsyncClient::mapCreateKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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. Prints out the details of the {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the - * {@link KeyVaultKey EC key} being created. - * - * @return The {@link KeyVaultKey created key}. - * - * @throws HttpResponseException If {@link CreateEcKeyOptions#getName()} is an empty string. - * @throws NullPointerException If {@code createEcKeyOptions} is {@code null}. - * @throws ResourceModifiedException If {@code createEcKeyOptions} is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey createEcKey(CreateEcKeyOptions createEcKeyOptions) { - return createEcKeyWithResponse(createEcKeyOptions, Context.NONE).getValue(); - } - - /** - * 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. Prints out the details of the {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the - * {@link KeyVaultKey EC key} being created. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 createEcKeyOptions} is {@code null}. - * @throws ResourceModifiedException If {@code createEcKeyOptions} is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { - if (createEcKeyOptions == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'createEcKeyOptions' cannot be null.")); - } - - Response response = callWithMappedException( - () -> implClient.createKeyWithResponse(vaultUrl, createEcKeyOptions.getName(), - createEcKeyOptions.getKeyType(), null, null, createEcKeyOptions.getKeyOperations(), - createKeyAttributes(createEcKeyOptions), createEcKeyOptions.getTags(), - createEcKeyOptions.getCurveName(), mapKeyReleasePolicy(createEcKeyOptions.getReleasePolicy()), context), - KeyAsyncClient::mapCreateKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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. Prints out the details of the newly {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the - * {@link KeyVaultKey symmetric key} being created. - * - * @return 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 KeyVaultKey createOctKey(CreateOctKeyOptions createOctKeyOptions) { - return createOctKeyWithResponse(createOctKeyOptions, Context.NONE).getValue(); - } - - /** - * 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. Prints out the details of the newly {@link KeyVaultKey created 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());
-     * 
- * - * - * @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the - * {@link KeyVaultKey symmetric key} being created. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 Response createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions, Context context) { - if (createOctKeyOptions == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'createOctKeyOptions' cannot be null.")); - } - - Response response = callWithMappedException(() -> implClient.createKeyWithResponse(vaultUrl, - createOctKeyOptions.getName(), createOctKeyOptions.getKeyType(), createOctKeyOptions.getKeySize(), null, - createOctKeyOptions.getKeyOperations(), createKeyAttributes(createOctKeyOptions), - createOctKeyOptions.getTags(), null, mapKeyReleasePolicy(createOctKeyOptions.getReleasePolicy()), context), - KeyAsyncClient::mapCreateKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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 the key vault. Prints out the details of the - * {@link KeyVaultKey imported key}.

- * - *
-     * KeyVaultKey key = keyClient.importKey("keyName", jsonWebKeyToImport);
-     *
-     * System.out.printf("Imported key with name: %s and id: %s%n", key.getName(), key.getId());
-     * 
- * - * - * @param name The name for the {@link KeyVaultKey imported key}. - * @param keyMaterial The {@link JsonWebKey} being imported. - * - * @return The {@link KeyVaultKey imported key}. - * - * @throws HttpResponseException If {@code name} is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey importKey(String name, JsonWebKey keyMaterial) { - return importKeyWithResponse(new ImportKeyOptions(name, keyMaterial), Context.NONE).getValue(); - } - - /** - * 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 the key vault. Prints out the details of the - * {@link KeyVaultKey imported 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());
-     * 
- * - * - * @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the - * {@link JsonWebKey} being imported. - * - * @return 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 KeyVaultKey importKey(ImportKeyOptions importKeyOptions) { - return importKeyWithResponse(importKeyOptions, Context.NONE).getValue(); - } - - /** - * 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 the key vault. Prints out the details of the - * {@link KeyVaultKey imported 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());
-     * 
- * - * - * @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the - * {@link JsonWebKey} being imported. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 keyImportOptions} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { - if (importKeyOptions == null) { - throw LOGGER.logExceptionAsError(new RuntimeException("'importKeyOptions' cannot be null.")); - } - - Response response = implClient.importKeyWithResponse(vaultUrl, importKeyOptions.getName(), - mapJsonWebKey(importKeyOptions.getKey()), importKeyOptions.isHardwareProtected(), - createKeyAttributes(importKeyOptions), importKeyOptions.getTags(), - mapKeyReleasePolicy(importKeyOptions.getReleasePolicy()), context); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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. Prints out the details of the - * {@link KeyVaultKey retrieved key}.

- * - *
-     * String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * KeyVaultKey keyWithVersion = keyClient.getKey("keyName", keyVersion);
-     *
-     * System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersion.getName(),
-     *     keyWithVersion.getId());
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. - * @param version The version of the {@link KeyVaultKey key} to retrieve. If this is an empty string or - * {@code null}, this call is equivalent to calling {@link KeyClient#getKey(String)}, with the latest version - * being retrieved. - * - * @return The requested {@link KeyVaultKey key}. The content of the {@link KeyVaultKey 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 KeyVaultKey getKey(String name, String version) { - return getKeyWithResponse(name, version, Context.NONE).getValue(); - } - - /** - * 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. Prints out the details of the - * {@link KeyVaultKey retrieved key}.

- * - *
-     * String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * 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());
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * @param version The version of the {@link KeyVaultKey key} to retrieve. If this is an empty string or - * {@code null}, this call is equivalent to calling {@link KeyClient#getKey(String)}, with the latest version - * being retrieved. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains the requested - * {@link KeyVaultKey key}. The content of the {@link KeyVaultKey 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 Response getKeyWithResponse(String name, String version, Context context) { - Response response - = callWithMappedException(() -> implClient.getKeyWithResponse(vaultUrl, name, version, context), - KeyVaultKeysUtils::mapGetKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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. Prints out the details of the - * {@link KeyVaultKey retrieved key}.

- * - *
-     * KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName");
-     *
-     * System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(),
-     *     keyWithVersionValue.getId());
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. - * - * @return 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 non null/empty and an invalid {@code name} is specified. - * @throws ResourceNotFoundException When a key with non null/empty {@code name} doesn't exist in the key vault. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey getKey(String name) { - return getKeyWithResponse(name, null, Context.NONE).getValue(); - } - - /** - * 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 the latest version of the {@link KeyVaultKey key}, changes its expiry time and - * {@link KeyOperation key operations} and the updates the {@link KeyVaultKey key} in 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());
-     * 
- * - * - * @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 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 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 KeyVaultKey updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { - return updateKeyPropertiesWithResponse(keyProperties, Context.NONE, keyOperations).getValue(); - } - - /** - * 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 the latest version of the {@link KeyVaultKey key}, changes its expiry time and - * {@link KeyOperation key operations} and the updates the {@link KeyVaultKey key} in 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());
-     * 
- * - * - * @param keyProperties The {@link KeyProperties key properties} object with updated properties. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * @param keyOperations The updated {@link KeyOperation key operations} to associate with the key. - * - * @return 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 Response updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, - KeyOperation... keyOperations) { - if (keyProperties == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'keyProperties' cannot be null.")); - } - - Response response - = implClient.updateKeyWithResponse(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), - keyOperations == null ? null : Arrays.asList(keyOperations), createKeyAttributes(keyProperties), - keyProperties.getTags(), mapKeyReleasePolicy(keyProperties.getReleasePolicy()), context); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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} from the key vault. Prints out the recovery id of the - * {@link KeyVaultKey deleted 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
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key} to be deleted. - * - * @return A {@link SyncPoller} to poll on and retrieve {@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.LONG_RUNNING_OPERATION) - public SyncPoller beginDeleteKey(String name) { - return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), - deletePollOperation(name), (pollingContext, firstResponse) -> null, pollingContext -> null); - } - - private Function, PollResponse> deleteActivationOperation(String name) { - return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, callWithMappedException( - () -> createDeletedKey(implClient.deleteKey(vaultUrl, name)), KeyAsyncClient::mapDeleteKeyException)); - } - - private Function, PollResponse> deletePollOperation(String name) { - return pollingContext -> { - try { - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedKey(implClient.getDeletedKey(vaultUrl, name))); - } catch (KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return 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 new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue()); - } - } catch (RuntimeException ex) { - // 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 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. Prints out the details - * of the {@link KeyVaultKey deleted key}.

- * - *
-     * DeletedKey deletedKey = keyClient.getDeletedKey("keyName");
-     *
-     * System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId());
-     * 
- * - * - * @param name The name of the deleted {@link KeyVaultKey key}. - * - * @return 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 DeletedKey getDeletedKey(String name) { - return getDeletedKeyWithResponse(name, Context.NONE).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. Prints out the details - * of the {@link KeyVaultKey deleted key} returned in the {@link Response HTTPresponse}.

- * - *
-     * Response<DeletedKey> deletedKeyResponse =
-     *     keyClient.getDeletedKeyWithResponse("keyName", new Context("key1", "value1"));
-     *
-     * System.out.printf("Deleted key with recovery id: %s%n", deletedKeyResponse.getValue().getRecoveryId());
-     * 
- * - * - * @param name The name of the deleted {@link KeyVaultKey key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 Response getDeletedKeyWithResponse(String name, Context context) { - Response response - = callWithMappedException(() -> implClient.getDeletedKeyWithResponse(vaultUrl, name, context), - KeyAsyncClient::mapGetDeletedKeyException); - - return new SimpleResponse<>(response, createDeletedKey(response.getValue())); - } - - /** - * 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.

- * - *
-     * keyClient.purgeDeletedKey("deletedKeyName");
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey 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 void purgeDeletedKey(String name) { - purgeDeletedKeyWithResponse(name, Context.NONE); - } - - /** - * 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.

- * - *
-     * Response<Void> purgeDeletedKeyResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName",
-     *     new Context("key1", "value1"));
-     *
-     * System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode());
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey deleted key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return A {@link 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 Response purgeDeletedKeyWithResponse(String name, Context context) { - return callWithMappedException(() -> implClient.purgeDeletedKeyWithResponse(vaultUrl, name, context), - KeyAsyncClient::mapPurgeDeletedKeyException); - } - - /** - * 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.

- * - *
-     * 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
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey deleted key} to be recovered. - * - * @return A {@link SyncPoller} to poll on and retrieve {@link KeyVaultKey recovered 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.LONG_RUNNING_OPERATION) - public SyncPoller beginRecoverDeletedKey(String name) { - return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), - recoverPollOperation(name), (pollingContext, firstResponse) -> null, pollingContext -> null); - } - - private Function, PollResponse> recoverActivationOperation(String name) { - return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createKeyVaultKey(callWithMappedException(() -> implClient.recoverDeletedKey(vaultUrl, name), - KeyAsyncClient::mapRecoverDeletedKeyException))); - } - - private Function, PollResponse> recoverPollOperation(String keyName) { - return pollingContext -> { - try { - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultKey(implClient.getKey(vaultUrl, keyName, null))); - } catch (KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return 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 new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue()); - } - } catch (RuntimeException ex) { - // 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. - return 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.

- * - *
-     * byte[] keyBackup = keyClient.backupKey("keyName");
-     *
-     * System.out.printf("Key backup byte array length: %s%n", keyBackup.length);
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}. - * - * @return 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 byte[] backupKey(String name) { - return backupKeyWithResponse(name, Context.NONE).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 and prints out the length of the key's backup byte - * array returned in the {@link Response HTTPresponse}.

- * - *
-     * Response<byte[]> backupKeyResponse = keyClient.backupKeyWithResponse("keyName", new Context("key1", "value1"));
-     *
-     * System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length);
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains 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 Response backupKeyWithResponse(String name, Context context) { - Response response = callWithMappedException( - () -> implClient.backupKeyWithResponse(vaultUrl, name, context), KeyAsyncClient::mapBackupKeyException); - - return new SimpleResponse<>(response, response.getValue().getValue()); - } - - /** - * 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.

- * // Pass the key backup byte array to the restore operation. - * - *
-     * byte[] keyBackupByteArray = {};
-     * KeyVaultKey keyResponse = keyClient.restoreKeyBackup(keyBackupByteArray);
-     * System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getName(), keyResponse.getId());
-     * 
- * - * - * @param backup The backup blob associated with the {@link KeyVaultKey key}. - * - * @return The {@link KeyVaultKey restored key}. - * - * @throws ResourceModifiedException When the {@code backup} blob is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey restoreKeyBackup(byte[] backup) { - return restoreKeyBackupWithResponse(backup, Context.NONE).getValue(); - } - - /** - * 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. Prints out the details of the - * {@link KeyVaultKey restored key} returned in the {@link Response HTTPresponse}.

- * // Pass the key backup byte array to the restore operation. - * - *
-     * 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());
-     * 
- * - * - * @param backup The backup blob associated with the {@link KeyVaultKey key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains the {@link KeyVaultKey restored key}. - * - * @throws ResourceModifiedException When the {@code backup} blob is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreKeyBackupWithResponse(byte[] backup, Context context) { - Response response = callWithMappedException( - () -> implClient.restoreKeyWithResponse(vaultUrl, backup, context), KeyAsyncClient::mapRestoreKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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. Loop over the - * {@link KeyProperties} and call {@link KeyClient#getKey(String, String)}. This will return the - * {@link KeyVaultKey key} with 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 {@link KeyVaultKey full keys} with key material from this information. Iterate over all - * the {@link KeyProperties} by page and call {@link KeyClient#getKey(String, String)}. This will return the - * {@link KeyVaultKey key} with 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());
-     *     });
-     * });
-     * 
- * - * - * @return {@link PagedIterable} of {@link KeyProperties key} of all the {@link KeyVaultKey keys} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listPropertiesOfKeys() { - return listPropertiesOfKeys(Context.NONE); - } - - /** - * 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. Loop over the - * {@link KeyProperties} and call {@link KeyClient#getKey(String, String)}. This will return the - * {@link KeyVaultKey key} with 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 {@link KeyVaultKey full keys} with key material from this information. Iterate over all - * the {@link KeyProperties} by page and call {@link KeyClient#getKey(String, String)}. This will return the - * {@link KeyVaultKey key} with 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());
-     *     });
-     * });
-     * 
- * - * - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return {@link PagedIterable} of {@link KeyProperties key} of all the {@link KeyVaultKey keys} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listPropertiesOfKeys(Context context) { - return new PagedIterable<>( - maxResults -> mapKeyItemPagedResponse(implClient.getKeysSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapKeyItemPagedResponse( - implClient.getKeysNextSinglePage(continuationToken, vaultUrl, context))); - } - - /** - * 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 and for each {@link DeletedKey deleted key} prints - * 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 {@link DeletedKey deleted keys} by 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()));
-     * });
-     * 
- * - * - * @return {@link PagedIterable} of all of the {@link DeletedKey deleted keys} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDeletedKeys() { - return listDeletedKeys(Context.NONE); - } - - /** - * 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 and for each {@link DeletedKey deleted key} prints - * 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 {@link DeletedKey deleted keys} by 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()));
-     * });
-     * 
- * - * - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return {@link PagedIterable} of all of the {@link DeletedKey deleted keys} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDeletedKeys(Context context) { - return new PagedIterable<>( - maxResults -> mapDeletedKeyItemPagedResponse( - implClient.getDeletedKeysSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapDeletedKeyItemPagedResponse( - implClient.getDeletedKeysNextSinglePage(continuationToken, vaultUrl, context))); - } - - /** - * 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. - * - *

It is possible to get {@link KeyVaultKey full keys} with key material for each version from this information. - * Loop over the {@link KeyProperties key} and call {@link KeyClient#getKey(String, String)}. This will return the - * {@link KeyVaultKey keys} with 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 {@link KeyVaultKey full keys} with key material for each version from this information. - * Iterate over all the {@link KeyProperties key} by page and call {@link KeyClient#getKey(String, String)}. This - * will return the {@link KeyVaultKey keys} with 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()));
-     * });
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}. - * - * @return {@link PagedIterable} of {@link KeyProperties key} of all the versions of the specified key in the vault. - * The list is empty if a {@link KeyVaultKey key} with the provided {@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 PagedIterable listPropertiesOfKeyVersions(String name) { - return listPropertiesOfKeyVersions(name, Context.NONE); - } - - /** - * 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. - * - *

It is possible to get {@link KeyVaultKey full keys} with key material for each version from this information. - * Loop over the {@link KeyProperties key} and call {@link KeyClient#getKey(String, String)}. This will return the - * {@link KeyVaultKey keys} with 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 {@link KeyVaultKey full keys} with key material for each version from this information. - * Iterate over all the {@link KeyProperties key} by page and call {@link KeyClient#getKey(String, String)}. This - * will return the {@link KeyVaultKey keys} with 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()));
-     * });
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return {@link PagedIterable} of {@link KeyProperties key} of all the versions of the specified - * {@link KeyVaultKey key} in the vault. The list is empty if a {@link KeyVaultKey key} with the provided - * {@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 PagedIterable listPropertiesOfKeyVersions(String name, Context context) { - return new PagedIterable<>( - maxResults -> mapKeyItemPagedResponse( - implClient.getKeyVersionsSinglePage(vaultUrl, name, maxResults, context)), - (continuationToken, maxResults) -> mapKeyItemPagedResponse( - implClient.getKeyVersionsNextSinglePage(continuationToken, vaultUrl, 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 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));
-     * 
- * - * - * @param count The requested number of random bytes. - * - * @return The requested number of bytes containing random values from a managed HSM. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public byte[] getRandomBytes(int count) { - return getRandomBytesWithResponse(count, Context.NONE).getValue(); - } - - /** - * 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;
-     * 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()));
-     * 
- * - * - * @param count The requested number of random bytes. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return 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 Response getRandomBytesWithResponse(int count, Context context) { - Response response = implClient.getRandomBytesWithResponse(vaultUrl, count, context); - - return new SimpleResponse<>(response, response.getValue().getValue()); - } - - /** - * 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}. 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);
-     * 
- * - * - * @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 The key release result containing the {@link KeyVaultKey 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 ReleaseKeyResult releaseKey(String name, String targetAttestationToken) { - return releaseKeyWithResponse(name, null, targetAttestationToken, new ReleaseKeyOptions(), Context.NONE) - .getValue(); - } - - /** - * Releases a specific 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}. Prints out the signed object that contains the release key.

- * - *
-     * String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * String myTargetAttestationToken = "someAttestationToken";
-     * ReleaseKeyResult releaseKeyVersionResult =
-     *     keyClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken);
-     *
-     * System.out.printf("Signed object containing released key: %s%n", releaseKeyVersionResult);
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key} to release. - * @param version The version of the key to release. If this is empty or {@code null}, this call is equivalent to - * calling {@link KeyClient#releaseKey(String, String)}, with the latest key version being released. - * @param targetAttestationToken The attestation assertion for the target of the {@link KeyVaultKey key} release. - * - * @return The key release result containing the {@link KeyVaultKey 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 ReleaseKeyResult releaseKey(String name, String version, String targetAttestationToken) { - return releaseKeyWithResponse(name, version, targetAttestationToken, new ReleaseKeyOptions(), Context.NONE) - .getValue(); - } - - /** - * Releases a {@link KeyVaultKey key}. - * - *

The key must be exportable. This operation requires the {@code keys/release} permission.

- * - *

Code Samples

- *

Releases a {@link KeyVaultKey key}. Prints out the - * {@link Response HTTP Response} details and the signed object that contains the release key.

- * - *
-     * String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * 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());
-     * 
- * - * - * @param name The name of the {@link KeyVaultKey key} to release. - * @param version The version of the {@link KeyVaultKey key} to release. If this is empty or {@code null}, this call - * is equivalent to calling {@link KeyClient#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}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return The {@link Response HTTP response} for this operation and the {@link ReleaseKeyResult} containing the - * {@link KeyVaultKey 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 Response releaseKeyWithResponse(String name, String version, String targetAttestationToken, - ReleaseKeyOptions releaseKeyOptions, Context context) { - if (CoreUtils.isNullOrEmpty(name) || CoreUtils.isNullOrEmpty(targetAttestationToken)) { - throw LOGGER.logExceptionAsError( - 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 callWithMappedException(() -> implClient.releaseWithResponse(vaultUrl, name, version, - targetAttestationToken, nonce, algorithm, context), KeyAsyncClient::mapReleaseKeyException); - } - - /** - * 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.

- * - *
-     * KeyVaultKey key = keyClient.rotateKey("keyName");
-     *
-     * 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 KeyVaultKey rotateKey(String name) { - return rotateKeyWithResponse(name, Context.NONE).getValue(); - } - - /** - * 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 the {@link Response HTTP Response} and - * {@link KeyVaultKey rotated key} details.

- * - *
-     * 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());
-     * 
- * - * - * @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the - * specified {@link KeyVaultKey key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return The {@link Response HTTP response} for this operation containing 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 Response rotateKeyWithResponse(String name, Context context) { - Response response = callWithMappedException( - () -> implClient.rotateKeyWithResponse(vaultUrl, name, context), KeyAsyncClient::mapRotateKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - /** - * 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}. Prints out the - * {@link KeyRotationPolicy rotation policy key} details.

- * - *
-     * KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy("keyName");
-     *
-     * System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId());
-     * 
- * - * - * @param keyName The name of the {@link KeyVaultKey key}. - * - * @return The {@link KeyRotationPolicy} for the {@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 KeyRotationPolicy getKeyRotationPolicy(String keyName) { - return getKeyRotationPolicyWithResponse(keyName, Context.NONE).getValue(); - } - - /** - * 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}. Prints out the - * {@link Response HTTP Response} and {@link KeyRotationPolicy rotation policy key} details.

- * - *
-     * 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());
-     * 
- * - * - * @param keyName The name of the {@link KeyVaultKey key}. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return A {@link Response HTTP response} for this operation containing the {@link KeyRotationPolicy} for the - * {@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 Response getKeyRotationPolicyWithResponse(String keyName, Context context) { - Response response - = callWithMappedException(() -> implClient.getKeyRotationPolicyWithResponse(vaultUrl, keyName, context), - KeyAsyncClient::mapGetKeyRotationPolicyException); - - return new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue())); - } - - /** - * Updates the {@link KeyRotationPolicy} of the {@link KeyVaultKey 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}. Prints out the - * {@link KeyRotationPolicy rotation policy key} details.

- * - *
-     * 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());
-     * 
- * - * - * @param keyName The name of the {@link KeyVaultKey key}. - * @param keyRotationPolicy The {@link KeyRotationPolicy} for the ke{@link KeyVaultKey key}y. - * - * @return The {@link KeyRotationPolicy} for the {@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 KeyRotationPolicy updateKeyRotationPolicy(String keyName, KeyRotationPolicy keyRotationPolicy) { - return updateKeyRotationPolicyWithResponse(keyName, keyRotationPolicy, Context.NONE).getValue(); - } - - /** - * 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}. Prints out the - * {@link Response HTTP Response} and {@link KeyRotationPolicy rotation policy key} details.

- * - *
-     * 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());
-     * 
- * - * - * @param keyName The name of the {@link KeyVaultKey key}. - * @param keyRotationPolicy The {@link KeyRotationPolicy} for the key. - * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service - * call. - * - * @return A {@link Response HTTP response} for this operation containing the {@link KeyRotationPolicy} for the - * {@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 Response updateKeyRotationPolicyWithResponse(String keyName, - KeyRotationPolicy keyRotationPolicy, Context context) { - Response response - = callWithMappedException( - () -> implClient.updateKeyRotationPolicyWithResponse(vaultUrl, keyName, - mapKeyRotationPolicy(keyRotationPolicy), context), - KeyAsyncClient::mapUpdateKeyRotationPolicyException); - - return new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue())); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java deleted file mode 100644 index 2756c32164cf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java +++ /dev/null @@ -1,511 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.TracingOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.tracing.Tracer; -import com.azure.core.util.tracing.TracerProvider; -import com.azure.security.keyvault.keys.implementation.KeyClientImpl; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.keys.implementation.KeyVaultErrorCodeStrings; -import com.azure.security.keyvault.keys.models.KeyVaultKeyIdentifier; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the {@link KeyAsyncClient - * secret async client} and {@link KeyClient secret sync client}, by calling - * {@link KeyClientBuilder#buildAsyncClient() buildAsyncClient} and {@link KeyClientBuilder#buildClient() buildClient} - * respectively. It constructs an instance of the desired client. - * - *

The minimal configuration options required by {@link KeyClientBuilder} to build a {@link KeyAsyncClient} are - * {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom - * {@link HttpClient http client} can be optionally configured in the {@link KeyClientBuilder}.

- * - * - *
- * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- *     .httpClient(HttpClient.createDefault())
- *     .buildAsyncClient();
- * 
- * - * - *

The minimal configuration options required by {@link KeyClientBuilder keyClientBuilder} to build {@link - * KeyClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyClient keyClient = new KeyClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - * @see KeyAsyncClient - * @see KeyClient - */ -@ServiceClientBuilder(serviceClients = KeyClient.class) -public final class KeyClientBuilder implements TokenCredentialTrait, HttpTrait, - ConfigurationTrait { - private static final ClientLogger LOGGER = new ClientLogger(KeyClientBuilder.class); - - private static final String CLIENT_NAME; - private static final String CLIENT_VERSION; - - static { - Map properties = CoreUtils.getProperties("azure-key-vault-keys.properties"); - CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); - CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); - } - - // Please see here - // for more information on Azure resource provider namespaces. - private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; - private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); - - private final List perCallPolicies; - private final List perRetryPolicies; - - private TokenCredential credential; - private HttpPipeline pipeline; - private String vaultUrl; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private Configuration configuration; - private KeyServiceVersion version; - private ClientOptions clientOptions; - private boolean disableChallengeResourceVerification = false; - - /** - * The constructor with defaults. - */ - public KeyClientBuilder() { - httpLogOptions = new HttpLogOptions(); - perCallPolicies = new ArrayList<>(); - perRetryPolicies = new ArrayList<>(); - } - - /** - * Creates a {@link KeyClient} based on options set in the builder. - * Every time {@code buildClient()} is called, a new instance of {@link KeyClient} is created. - * - *

If {@link KeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link KeyClientBuilder#vaultUrl(String) vaultUrl} are used to create the {@link KeyClientBuilder client}. - * All other builder settings are ignored. If {@code pipeline} is not set, then {@link - * KeyClientBuilder#credential(TokenCredential) key vault credential} and {@link - * KeyClientBuilder#vaultUrl(String) key vault url} are required to build the {@link KeyClient client}.

- * - * @return A {@link KeyClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link KeyClientBuilder#credential(TokenCredential)} or - * {@link KeyClientBuilder#vaultUrl(String)} have not been set. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public KeyClient buildClient() { - return new KeyClient(buildInnerClient(), vaultUrl, version != null ? version : KeyServiceVersion.getLatest()); - } - - /** - * Creates a {@link KeyAsyncClient} based on options set in the builder. - * Every time {@code buildAsyncClient()} is called, a new instance of {@link KeyAsyncClient} is created. - * - *

If {@link KeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link KeyClientBuilder#vaultUrl(String) vaultUrl} are used to create the {@link KeyClientBuilder client}. - * All other builder settings are ignored. If {@code pipeline} is not set, then {@link - * KeyClientBuilder#credential(TokenCredential) key vault credential} and {@link KeyClientBuilder#vaultUrl(String)} - * key vault url are required to build the {@link KeyAsyncClient client}.

- * - * @return A {@link KeyAsyncClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link KeyClientBuilder#credential(TokenCredential)} or - * {@link KeyClientBuilder#vaultUrl(String)} have not been set. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public KeyAsyncClient buildAsyncClient() { - return new KeyAsyncClient(buildInnerClient(), vaultUrl, - version != null ? version : KeyServiceVersion.getLatest()); - } - - private KeyClientImpl buildInnerClient() { - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; - String buildEndpoint = getBuildEndpoint(buildConfiguration); - - if (buildEndpoint == null) { - throw LOGGER - .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); - } - - KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); - - if (pipeline != null) { - return new KeyClientImpl(pipeline, serviceVersion.getVersion()); - } - - if (credential == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.CREDENTIALS_REQUIRED)); - } - - // Closest to API goes first, closest to wire goes last. - final List policies = new ArrayList<>(); - - httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - ClientOptions localClientOptions = clientOptions != null ? clientOptions : DEFAULT_CLIENT_OPTIONS; - - policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), CLIENT_NAME, - CLIENT_VERSION, buildConfiguration)); - - HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions); - if (headers != null) { - policies.add(new AddHeadersPolicy(new HttpHeaders(headers))); - } - - // Add per call additional policies. - policies.addAll(perCallPolicies); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - // Add retry policy. - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - - policies.add(new KeyVaultCredentialPolicy(credential, disableChallengeResourceVerification)); - // Add per retry additional policies. - policies.addAll(perRetryPolicies); - - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - - TracingOptions tracingOptions = localClientOptions.getTracingOptions(); - Tracer tracer = TracerProvider.getDefaultProvider() - .createTracer(CLIENT_NAME, CLIENT_VERSION, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .tracer(tracer) - .clientOptions(localClientOptions) - .build(); - - return new KeyClientImpl(pipeline, serviceVersion.getVersion()); - } - - /** - * Sets the vault endpoint URL to send HTTP requests to. You should validate that this URL references a valid Key - * Vault or Managed HSM resource. Refer to the following - * documentation for details. - * - * @param vaultUrl The vault url is used as destination on Azure to send requests to. If you have a key identifier, - * create a new {@link KeyVaultKeyIdentifier} to parse it and obtain the {@code vaultUrl} and other - * information. - * - * @return The updated {@link KeyClientBuilder} object. - * - * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. - * @throws NullPointerException If {@code vaultUrl} is {@code null}. - */ - public KeyClientBuilder vaultUrl(String vaultUrl) { - if (vaultUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); - } - - try { - URL url = new URL(vaultUrl); - this.vaultUrl = url.toString(); - } catch (MalformedURLException ex) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault url is malformed.", ex)); - } - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link KeyClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public KeyClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - this.credential = credential; - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated {@link KeyClientBuilder} object. - */ - @Override - public KeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated {@link KeyClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public KeyClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated {@link KeyClientBuilder} object. - */ - @Override - public KeyClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * The {@link #vaultUrl(String) vaultUrl} is not ignored when - * {@code pipeline} is set. - * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated {@link KeyClientBuilder} object. - */ - @Override - public KeyClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - - return this; - } - - /** - * Sets the {@link KeyServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param version {@link KeyServiceVersion} of the service to be used when making requests. - * - * @return The updated {@link KeyClientBuilder} object. - */ - public KeyClientBuilder serviceVersion(KeyServiceVersion version) { - this.version = version; - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store used to get configuration details. - * - * @return The updated {@link KeyClientBuilder} object. - */ - @Override - public KeyClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. - *

- * The default retry policy will be used in the pipeline, if not provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy user's retry policy applied to each request. - * - * @return The updated {@link KeyClientBuilder} object. - */ - public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated {@link KeyClientBuilder} object. - */ - @Override - public KeyClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @see HttpClientOptions - * @return The updated {@link KeyClientBuilder} object. - */ - @Override - public KeyClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault or Managed HSM domain. This - * verification is performed by default. - * - * @return The updated {@link KeyClientBuilder} object. - */ - public KeyClientBuilder disableChallengeResourceVerification() { - this.disableChallengeResourceVerification = true; - - return this; - } - - private String getBuildEndpoint(Configuration configuration) { - if (vaultUrl != null) { - return vaultUrl; - } - - String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); - if (CoreUtils.isNullOrEmpty(configEndpoint)) { - return null; - } - - try { - URL url = new URL(configEndpoint); - return url.toString(); - } catch (MalformedURLException ex) { - return null; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java deleted file mode 100644 index c335fdc6e383..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.util.ServiceVersion; - -/** - * The versions of Azure Key Vault Key supported by this client library. - */ -public enum KeyServiceVersion implements ServiceVersion { - /** - * Service version {@code 7.0}. - */ - V7_0("7.0"), - - /** - * Service version {@code 7.1}. - */ - V7_1("7.1"), - - /** - * Service version {@code 7.2}. - */ - V7_2("7.2"), - - /** - * Service version {@code 7.3}. - */ - V7_3("7.3"), - - /** - * Service version {@code 7.4-preview.1}. - */ - V7_4("7.4"), - - /** - * Service version {@code 7.5}. - */ - V7_5("7.5"), - - /** - * Service version {@code 7.6-preview.1}. - */ - V7_6_PREVIEW_1("7.6-preview.1"); - - private final String version; - - KeyServiceVersion(String version) { - this.version = version; - } - - /** - * {@inheritDoc} - */ - @Override - public String getVersion() { - return this.version; - } - - /** - * Gets the latest service version supported by this client library - * - * @return the latest {@link KeyServiceVersion} - */ - public static KeyServiceVersion getLatest() { - return V7_6_PREVIEW_1; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java deleted file mode 100644 index 04e88a78eb86..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java +++ /dev/null @@ -1,907 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.Response; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.security.keyvault.keys.cryptography.implementation.CryptographyClientImpl; -import com.azure.security.keyvault.keys.cryptography.implementation.LocalKeyCryptographyClient; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.implementation.KeyClientImpl; -import com.azure.security.keyvault.keys.implementation.SecretMinClientImpl; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import reactor.core.publisher.Mono; - -import java.util.Objects; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.withContext; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.createLocalClient; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.isThrowableRetryable; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.retrieveJwkAndCreateLocalAsyncClient; - -/** - * The {@link CryptographyAsyncClient} provides asynchronous methods to perform cryptographic operations using - * asymmetric and symmetric keys. The client supports encrypt, decrypt, wrap key, unwrap key, sign and verify - * operations using the configured key. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link CryptographyAsyncClient} 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 Cryptography Client

- * - *

The following code sample demonstrates the creation of a {@link CryptographyAsyncClient}, using the - * {@link CryptographyClientBuilder} to configure it.

- * - * - *
- * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
- *     .keyIdentifier("<your-key-id>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
- * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
- *     .jsonWebKey(jsonWebKey)
- *     .buildAsyncClient();
- * 
- * - *
- * - *

When a {@link CryptographyAsyncClient} gets created using a {@code Azure Key Vault key identifier}, the first - * time a cryptographic operation is attempted, the client will attempt to retrieve the key material from the service, - * cache it, and perform all future cryptographic operations locally, deferring to the service when that's not possible. - * If key retrieval and caching fails because of a non-retryable error, the client will not make any further attempts - * and will fall back to performing all cryptographic operations on the service side. Conversely, when a - * {@link CryptographyAsyncClient} created using a {@link JsonWebKey JSON Web Key}, all cryptographic operations will be - * performed locally.

- * - *
- * - *

Encrypt Data

- * The {@link CryptographyAsyncClient} can be used to encrypt data. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously encrypt data using the - * {@link CryptographyAsyncClient#encrypt(EncryptionAlgorithm, byte[])} API.

- * - * - *
- * byte[] plaintext = new byte[100];
- * new Random(0x1234567L).nextBytes(plaintext);
- *
- * cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext)
- *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
- *     .subscribe(encryptResult ->
- *         System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
- *             encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link CryptographyClient}.

- * - *
- * - *
- * - *

Decrypt Data

- * The {@link CryptographyAsyncClient} can be used to decrypt data. - * - *

Code Sample:

- * - *

The following code sample demonstrates how to asynchronously decrypt data using the - * {@link CryptographyAsyncClient#decrypt(EncryptionAlgorithm, byte[])} API.

- * - * - *
- * byte[] ciphertext = new byte[100];
- * new Random(0x1234567L).nextBytes(ciphertext);
- *
- * cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext)
- *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
- *     .subscribe(decryptResult ->
- *         System.out.printf("Received decrypted content of length: %d%n", decryptResult.getPlainText().length));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link CryptographyClient}.

- * - * @see com.azure.security.keyvault.keys.cryptography - * @see CryptographyClientBuilder - */ -@ServiceClient( - builder = CryptographyClientBuilder.class, - isAsync = true, - serviceInterfaces = { KeyClientImpl.KeyClientService.class, SecretMinClientImpl.SecretMinClientService.class }) -public class CryptographyAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(CryptographyAsyncClient.class); - - private final HttpPipeline pipeline; - - private volatile boolean skipLocalClientCreation; - private volatile LocalKeyCryptographyClient localKeyCryptographyClient; - - final CryptographyClientImpl implClient; - final String keyId; - - /** - * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. - * - * @param keyId The Azure Key Vault key identifier to use for cryptography operations. - * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. - * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. - * @param disableKeyCaching Indicates if local key caching should be disabled and all cryptographic operations - * deferred to the service. - */ - CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version, - boolean disableKeyCaching) { - this.implClient = new CryptographyClientImpl(keyId, pipeline, version); - this.keyId = keyId; - this.pipeline = pipeline; - this.skipLocalClientCreation = disableKeyCaching; - } - - /** - * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography - * operations. - * - * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. - */ - CryptographyAsyncClient(JsonWebKey jsonWebKey) { - Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); - - if (!jsonWebKey.isValid()) { - throw new IllegalArgumentException("The JSON Web Key is not valid."); - } - - if (jsonWebKey.getKeyOps() == null) { - throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); - } - - if (jsonWebKey.getKeyType() == null) { - throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); - } - - this.implClient = null; - this.keyId = jsonWebKey.getId(); - this.pipeline = null; - - try { - this.localKeyCryptographyClient = createLocalClient(jsonWebKey, null); - } catch (RuntimeException e) { - throw LOGGER - .logExceptionAsError(new RuntimeException("Could not initialize local cryptography client.", e)); - } - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.pipeline; - } - - /** - * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires - * the {@code keys/get} permission for non-local operations. - * - *

Code Samples

- *

Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key - * details when a response has been received.

- * - * - *
-     * cryptographyAsyncClient.getKey()
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(key ->
-     *         System.out.printf("Key returned with name: %s, and id: %s.%n", key.getName(), key.getId()));
-     * 
- * - * - * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. - * - * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKey() { - return getKeyWithResponse().flatMap(FluxUtil::toMono); - } - - /** - * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires - * the {@code keys/get} permission for non-local operations. - * - *

Code Samples

- *

Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key - * details when a response has been received.

- * - * - *
-     * cryptographyAsyncClient.getKeyWithResponse()
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(keyResponse ->
-     *         System.out.printf("Key returned with name: %s, and id: %s.%n", keyResponse.getValue().getName(),
-     *             keyResponse.getValue().getId()));
-     * 
- * - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * requested {@link KeyVaultKey key}. - * - * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. - * @throws UnsupportedOperationException When operating in local-only mode (using a client created using a - * JsonWebKey instance). - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyWithResponse() { - if (implClient != null) { - try { - return implClient.getKeyAsync(); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } else { - return monoError(LOGGER, - new UnsupportedOperationException("Operation not supported when operating in local-only mode.")); - } - } - - /** - * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports - * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be - * used. - * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the - * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission - * for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting - * the - * specified {@code plaintext}. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when - * a response has been received.

- * - * - *
-     * byte[] plaintext = new byte[100];
-     * new Random(0x1234567L).nextBytes(plaintext);
-     *
-     * cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(encryptResult ->
-     *         System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
-     *             encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()));
-     * 
- * - * - * @param algorithm The algorithm to be used for encryption. - * @param plaintext The content to be encrypted. - * - * @return A {@link Mono} containing a {@link EncryptResult} whose - * {@link EncryptResult#getCipherText() cipher text} contains the encrypted content. - * - * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context); - } else { - return implClient.encryptAsync(algorithm, plaintext, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports - * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be - * used. - * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the - * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission - * for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting - * the - * specified {@code plaintext}. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when - * a response has been received.

- * - * - *
-     * byte[] plaintextBytes = new byte[100];
-     * new Random(0x1234567L).nextBytes(plaintextBytes);
-     * byte[] iv = {
-     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
-     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
-     * };
-     *
-     * EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(plaintextBytes, iv);
-     *
-     * cryptographyAsyncClient.encrypt(encryptParameters)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(encryptResult ->
-     *         System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
-     *             encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()));
-     * 
- * - * - * @param encryptParameters The parameters to use in the encryption operation. - * - * @return A {@link Mono} containing a {@link EncryptResult} whose - * {@link EncryptResult#getCipherText() cipher text} contains the encrypted content. - * - * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono encrypt(EncryptParameters encryptParameters) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.encryptAsync(encryptParameters, context); - } else { - return implClient.encryptAsync(encryptParameters, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a - * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm - * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires - * the {@code keys/decrypt} permission for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting - * the specified encrypted content. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content - * details when a response has been received.

- * - * - *
-     * byte[] ciphertext = new byte[100];
-     * new Random(0x1234567L).nextBytes(ciphertext);
-     *
-     * cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(decryptResult ->
-     *         System.out.printf("Received decrypted content of length: %d%n", decryptResult.getPlainText().length));
-     * 
- * - * - * @param algorithm The algorithm to be used for decryption. - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. - * See Timing - * vulnerabilities with CBC-mode symmetric decryption using padding for more information. - * - * @return A {@link Mono} containing the decrypted blob. - * - * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for decryption. - * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.decryptAsync(algorithm, ciphertext, context); - } else { - return implClient.decryptAsync(algorithm, ciphertext, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a - * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm - * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires - * the {@code keys/decrypt} permission for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting - * the specified encrypted content. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content - * details when a response has been received.

- * - * - *
-     * byte[] ciphertextBytes = new byte[100];
-     * new Random(0x1234567L).nextBytes(ciphertextBytes);
-     * byte[] iv = {
-     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
-     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
-     * };
-     *
-     * DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(ciphertextBytes, iv);
-     *
-     * cryptographyAsyncClient.decrypt(decryptParameters)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(decryptResult ->
-     *         System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length));
-     * 
- * - * - * @param decryptParameters The parameters to use in the decryption operation. Microsoft recommends you not use CBC - * without first ensuring the integrity of the ciphertext using an HMAC, for example. - * See Timing vulnerabilities - * with CBC-mode symmetric decryption using padding for more information. - * - * @return A {@link Mono} containing the decrypted blob. - * - * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for decryption. - * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono decrypt(DecryptParameters decryptParameters) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.decryptAsync(decryptParameters, context); - } else { - return implClient.decryptAsync(decryptParameters, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and - * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the - * signature from the digest. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response - * has been received.

- * - * - *
-     * byte[] data = new byte[100];
-     * new Random(0x1234567L).nextBytes(data);
-     * MessageDigest md = MessageDigest.getInstance("SHA-256");
-     * md.update(data);
-     * byte[] digest = md.digest();
-     *
-     * cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, digest)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(signResult ->
-     *         System.out.printf("Received signature of length: %d, with algorithm: %s.%n",
-     *             signResult.getSignature().length, signResult.getAlgorithm()));
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param digest The content from which signature is to be created. - * - * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult#getSignature() signature} - * contains the created signature. - * - * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for signing. - * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono sign(SignatureAlgorithm algorithm, byte[] digest) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.signAsync(algorithm, digest, context); - } else { - return implClient.signAsync(algorithm, digest, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric - * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation - * requires the {@code keys/verify} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the - * signature. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the - * verification details when a response has been received.

- * - * - *
-     * byte[] myData = new byte[100];
-     * new Random(0x1234567L).nextBytes(myData);
-     * MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
-     * messageDigest.update(myData);
-     * byte[] myDigest = messageDigest.digest();
-     *
-     * // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation.
-     * cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myDigest, signature)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(verifyResult ->
-     *         System.out.printf("Verification status: %s.%n", verifyResult.isValid()));
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param digest The content from which signature was created. - * @param signature The signature to be verified. - * - * @return A {@link Mono} containing a {@link VerifyResult} - * {@link VerifyResult#isValid() indicating the signature verification result}. - * - * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for verifying. - * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context); - } else { - return implClient.verifyAsync(algorithm, digest, signature, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both - * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local - * operations. - * - *

The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified - * key content. Possible values include: - * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128KW A128KW}, - * {@link EncryptionAlgorithm#A192KW A192KW} and {@link EncryptionAlgorithm#A256KW A256KW}.

- * - *

Code Samples

- *

Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a - * response has been received.

- * - * - *
-     * byte[] key = new byte[100];
-     * new Random(0x1234567L).nextBytes(key);
-     *
-     * cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(wrapResult ->
-     *         System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n",
-     *             wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm().toString()));
-     * 
- * - * - * @param algorithm The encryption algorithm to use for wrapping the key. - * @param key The key content to be wrapped. - * - * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult#getEncryptedKey() encrypted key} - * contains the wrapped key result. - * - * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for wrap operation. - * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context); - } else { - return implClient.wrapKeyAsync(algorithm, key, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation - * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. - * This - * operation requires the {@code keys/unwrapKey} permission for non-local operations. - * - *

The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the - * specified encrypted key content. Possible values for asymmetric keys include: - * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link KeyWrapAlgorithm#A128KW A128KW}, - * {@link KeyWrapAlgorithm#A192KW A192KW} and {@link KeyWrapAlgorithm#A256KW A256KW}.

- * - *

Code Samples

- *

Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when - * a response has been received.

- * - * - *
-     * byte[] keyToWrap = new byte[100];
-     * new Random(0x1234567L).nextBytes(key);
-     *
-     * cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(wrapResult ->
-     *         cryptographyAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapResult.getEncryptedKey())
-     *             .subscribe(keyUnwrapResult ->
-     *                 System.out.printf("Received key of length: %d.%n", keyUnwrapResult.getKey().length)));
-     * 
- * - * - * @param algorithm The encryption algorithm to use for wrapping the key. - * @param encryptedKey The encrypted key content to unwrap. - * - * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult#getKey() decrypted - * key} contains the unwrapped key result. - * - * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for wrap operation. - * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context); - } else { - return implClient.unwrapKeyAsync(algorithm, encryptedKey, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric - * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. - * Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a - * response has been received.

- * - * - *
-     * byte[] data = new byte[100];
-     * new Random(0x1234567L).nextBytes(data);
-     *
-     * cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, data)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(signResult ->
-     *         System.out.printf("Received signature of length: %d, with algorithm: %s.%n",
-     *             signResult.getSignature().length, signResult.getAlgorithm()));
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param data The content from which signature is to be created. - * - * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult#getSignature() signature} - * contains the created signature. - * - * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for signing. - * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono signData(SignatureAlgorithm algorithm, byte[] data) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.signDataAsync(algorithm, data, context); - } else { - return implClient.signDataAsync(algorithm, data, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric - * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. - * This operation requires the {@code keys/verify} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the - * signature. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the - * verification details when a response has been received.

- * - * - *
-     * byte[] myData = new byte[100];
-     * new Random(0x1234567L).nextBytes(myData);
-     *
-     * // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation.
-     * cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myData, signature)
-     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
-     *     .subscribe(verifyResult ->
-     *         System.out.printf("Verification status: %s.%n", verifyResult.isValid()));
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param data The raw content against which signature is to be verified. - * @param signature The signature to be verified. - * - * @return A {@link Mono} containing a {@link VerifyResult} - * {@link VerifyResult#isValid() indicating the signature verification result}. - * - * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for verifying. - * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { - try { - return withContext(context -> isLocalClientAvailable().flatMap(available -> { - if (available) { - return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context); - } else { - return implClient.verifyDataAsync(algorithm, data, signature, context); - } - })); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - private Mono isLocalClientAvailable() { - if (!skipLocalClientCreation && localKeyCryptographyClient == null) { - return retrieveJwkAndCreateLocalAsyncClient(implClient).map(localClient -> { - localKeyCryptographyClient = localClient; - - return true; - }).onErrorResume(t -> { - if (isThrowableRetryable(t)) { - LOGGER.log(LogLevel.VERBOSE, () -> "Could not set up local cryptography for this operation. " - + "Defaulting to service-side cryptography.", t); - } else { - skipLocalClientCreation = true; - - LOGGER.log(LogLevel.VERBOSE, () -> "Could not set up local cryptography. Defaulting to" - + "service-side cryptography for all operations.", t); - } - - return Mono.just(false); - }); - } - - return Mono.just(localKeyCryptographyClient != null); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java deleted file mode 100644 index eedd85400103..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java +++ /dev/null @@ -1,1233 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.security.keyvault.keys.cryptography.implementation.CryptographyClientImpl; -import com.azure.security.keyvault.keys.cryptography.implementation.LocalKeyCryptographyClient; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.implementation.KeyClientImpl; -import com.azure.security.keyvault.keys.implementation.SecretMinClientImpl; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import reactor.core.publisher.Mono; - -import java.util.Objects; - -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.createLocalClient; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.isThrowableRetryable; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.retrieveJwkAndCreateLocalClient; - -/** - * The {@link CryptographyClient} provides synchronous methods to perform cryptographic operations using asymmetric and - * symmetric keys. The client supports encrypt, decrypt, wrap key, unwrap key, sign and verify operations using the - * configured key. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link CryptographyClient} 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 Cryptography Client

- * - *

The following code sample demonstrates the creation of a {@link CryptographyClient}, using the - * {@link CryptographyClientBuilder} to configure it.

- * - * - *
- * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
- *     .keyIdentifier("<your-key-id>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *
- * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
- * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
- *     .jsonWebKey(jsonWebKey)
- *     .buildClient();
- * 
- * - * - *

When a {@link CryptographyClient} gets created using a {@code Azure Key Vault key identifier}, the first time a - * cryptographic operation is attempted, the client will attempt to retrieve the key material from the service, cache - * it, and perform all future cryptographic operations locally, deferring to the service when that's not possible. If - * key retrieval and caching fails because of a non-retryable error, the client will not make any further attempts and - * will fall back to performing all cryptographic operations on the service side. Conversely, when a - * {@link CryptographyClient} created using a {@link JsonWebKey JSON Web Key}, all cryptographic operations will be - * performed locally.

- * - *
- * - *
- * - *

Encrypt Data

- * The {@link CryptographyClient} can be used to encrypt data. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously encrypt data using the - * {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[])} API. - *

- * - * - *
- * byte[] plaintext = new byte[100];
- * new Random(0x1234567L).nextBytes(plaintext);
- *
- * EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext);
- *
- * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
- *     encryptResult.getCipherText().length, encryptResult.getAlgorithm());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link CryptographyAsyncClient}.

- * - *
- * - *
- * - *

Decrypt Data

- * The {@link CryptographyClient} can be used to decrypt data. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously decrypt data using the - * {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[])} API.

- * - * - *
- * byte[] ciphertext = new byte[100];
- * new Random(0x1234567L).nextBytes(ciphertext);
- *
- * DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext);
- *
- * System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length);
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link CryptographyAsyncClient}.

- * - * @see com.azure.security.keyvault.keys.cryptography - * @see CryptographyClientBuilder - */ -@ServiceClient( - builder = CryptographyClientBuilder.class, - serviceInterfaces = { KeyClientImpl.KeyClientService.class, SecretMinClientImpl.SecretMinClientService.class }) -public class CryptographyClient { - private static final ClientLogger LOGGER = new ClientLogger(CryptographyClient.class); - - private volatile boolean skipLocalClientCreation; - private volatile LocalKeyCryptographyClient localKeyCryptographyClient; - - final CryptographyClientImpl implClient; - final String keyId; - - /** - * Creates a {@link CryptographyClient} that uses a given {@link HttpPipeline pipeline} to service requests. - * - * @param keyId The Azure Key Vault key identifier to use for cryptography operations. - * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. - * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. - * @param disableKeyCaching Indicates if local key caching should be disabled and all cryptographic operations - * deferred to the service. - */ - CryptographyClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version, - boolean disableKeyCaching) { - this.implClient = new CryptographyClientImpl(keyId, pipeline, version); - this.keyId = keyId; - this.skipLocalClientCreation = disableKeyCaching; - } - - /** - * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography - * operations. - * - * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. - */ - CryptographyClient(JsonWebKey jsonWebKey) { - Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); - - if (!jsonWebKey.isValid()) { - throw new IllegalArgumentException("The JSON Web Key is not valid."); - } - - if (jsonWebKey.getKeyOps() == null) { - throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); - } - - if (jsonWebKey.getKeyType() == null) { - throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); - } - - this.implClient = null; - this.keyId = jsonWebKey.getId(); - - try { - this.localKeyCryptographyClient = createLocalClient(jsonWebKey, null); - } catch (RuntimeException e) { - throw LOGGER - .logExceptionAsError(new RuntimeException("Could not initialize local cryptography client.", e)); - } - } - - /** - * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires - * the {@code keys/get} permission for non-local operations. - * - *

Code Samples

- *

Gets the configured key in the client and prints out the returned key details when a response has been - * received.

- * - * - *
-     * KeyVaultKey key = cryptographyClient.getKey();
-     *
-     * System.out.printf("Key returned with name: %s and id: %s.%n", key.getName(), key.getId());
-     * 
- * - * - * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. - * - * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultKey getKey() { - return getKeyWithResponse(Context.NONE).getValue(); - } - - /** - * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires - * the {@code keys/get} permission for non-local operations. - * - *

Code Samples

- *

Gets the configured key in the client and prints out the returned key details when a response has been - * received.

- * - * - *
-     * KeyVaultKey keyWithVersion = cryptographyClient.getKeyWithResponse(new Context("key1", "value1")).getValue();
-     *
-     * System.out.printf("Key is returned with name: %s and id %s.%n", keyWithVersion.getName(),
-     *     keyWithVersion.getId());
-     * 
- * - * - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * requested {@link KeyVaultKey key}. - * - * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. - * @throws UnsupportedOperationException When operating in local-only mode (using a client created using a - * JsonWebKey instance). - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKeyWithResponse(Context context) { - if (implClient != null) { - return implClient.getKey(context); - } else { - throw LOGGER.logExceptionAsError( - new UnsupportedOperationException("Operation not supported when operating in local-only mode.")); - } - } - - /** - * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports - * a - * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. - * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the - * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission - * for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting - * the specified {@code plaintext}. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Encrypts the content and prints out the encrypted content details when a response has been received.

- * - * - *
-     * byte[] plaintext = new byte[100];
-     * new Random(0x1234567L).nextBytes(plaintext);
-     *
-     * EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext);
-     *
-     * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
-     *     encryptResult.getCipherText().length, encryptResult.getAlgorithm());
-     * 
- * - * - * @param algorithm The algorithm to be used for encryption. - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptResult} whose {@link EncryptResult#getCipherText() cipher text} contains the encrypted - * content. - * - * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { - return encrypt(algorithm, plaintext, Context.NONE); - } - - /** - * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports - * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be - * used. - * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the - * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission - * for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting - * the specified {@code plaintext}. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Encrypts the content prints out the encrypted content details when a response has been received.

- * - * - *
-     * byte[] plaintextToEncrypt = new byte[100];
-     * new Random(0x1234567L).nextBytes(plaintextToEncrypt);
-     *
-     * EncryptResult encryptionResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintextToEncrypt,
-     *     new Context("key1", "value1"));
-     *
-     * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
-     *     encryptionResult.getCipherText().length, encryptionResult.getAlgorithm());
-     * 
- * - * - * @param algorithm The algorithm to be used for encryption. - * @param plaintext The content to be encrypted. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return The {@link EncryptResult} whose {@link EncryptResult#getCipherText() cipher text} contains the encrypted - * content. - * - * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.encrypt(algorithm, plaintext, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.encrypt(algorithm, plaintext, context); - } - } - - /** - * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports - * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be - * used. - * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the - * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission - * for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting - * the specified {@code plaintext}. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Encrypts the content prints out the encrypted content details when a response has been received.

- * - * - *
-     * byte[] myPlaintext = new byte[100];
-     * new Random(0x1234567L).nextBytes(myPlaintext);
-     * byte[] iv = {
-     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
-     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
-     * };
-     *
-     * EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(myPlaintext, iv);
-     * EncryptResult encryptedResult = cryptographyClient.encrypt(encryptParameters, new Context("key1", "value1"));
-     *
-     * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
-     *     encryptedResult.getCipherText().length, encryptedResult.getAlgorithm());
-     * 
- * - * - * @param encryptParameters The parameters to use in the encryption operation. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return The {@link EncryptResult} whose {@link EncryptResult#getCipherText() cipher text} contains the encrypted - * content. - * - * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public EncryptResult encrypt(EncryptParameters encryptParameters, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.encrypt(encryptParameters, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.encrypt(encryptParameters, context); - } - } - - /** - * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a - * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm - * to - * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires - * the {@code keys/decrypt} permission for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting - * the specified encrypted content. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Decrypts the encrypted content prints out the decrypted content details when a response has been - * received.

- * - * - *
-     * byte[] ciphertext = new byte[100];
-     * new Random(0x1234567L).nextBytes(ciphertext);
-     *
-     * DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext);
-     *
-     * System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length);
-     * 
- * - * - * @param algorithm The algorithm to be used for decryption. - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. - * See Timing vulnerabilities - * with CBC-mode symmetric decryption using padding for more information. - * - * @return The {@link DecryptResult} whose {@link DecryptResult#getPlainText() plain text} contains the decrypted - * content. - * - * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for decryption. - * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { - return decrypt(algorithm, ciphertext, Context.NONE); - } - - /** - * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a - * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm - * to - * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires - * the {@code keys/decrypt} permission for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting - * the specified encrypted content. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Decrypts the encrypted content prints out the decrypted content details when a response has been - * received.

- * - * - *
-     * byte[] ciphertextToDecrypt = new byte[100];
-     * new Random(0x1234567L).nextBytes(ciphertextToDecrypt);
-     *
-     * DecryptResult decryptionResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertextToDecrypt,
-     *     new Context("key1", "value1"));
-     *
-     * System.out.printf("Received decrypted content of length: %d.%n", decryptionResult.getPlainText().length);
-     * 
- * - * - * @param algorithm The algorithm to be used for decryption. - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. - * See Timing vulnerabilities - * with CBC-mode symmetric decryption using padding for more information. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return The {@link DecryptResult} whose {@link DecryptResult#getPlainText() plain text} contains the decrypted - * content. - * - * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for decryption. - * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.decrypt(algorithm, ciphertext, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.decrypt(algorithm, ciphertext, context); - } - } - - /** - * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a - * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm - * to - * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires - * the {@code keys/decrypt} permission for non-local operations. - * - *

The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting - * the specified encrypted content. Possible values for asymmetric keys include: - * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, - * {@link EncryptionAlgorithm#A128CBCPAD A128CBCPAD}, {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, - * {@link EncryptionAlgorithm#A128GCM A128GCM}, {@link EncryptionAlgorithm#A192CBC A192CBC}, - * {@link EncryptionAlgorithm#A192CBCPAD A192CBCPAD}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, - * {@link EncryptionAlgorithm#A192GCM A192GCM}, {@link EncryptionAlgorithm#A256CBC A256CBC}, - * {@link EncryptionAlgorithm#A256CBCPAD A256CBPAD}, {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} and - * {@link EncryptionAlgorithm#A256GCM A256GCM}.

- * - *

Code Samples

- *

Decrypts the encrypted content prints out the decrypted content details when a response has been - * received.

- * - * - *
-     * byte[] myCiphertext = new byte[100];
-     * new Random(0x1234567L).nextBytes(myCiphertext);
-     * byte[] iv = {
-     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
-     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
-     * };
-     *
-     * DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(myCiphertext, iv);
-     * DecryptResult decryptedResult = cryptographyClient.decrypt(decryptParameters, new Context("key1", "value1"));
-     *
-     * System.out.printf("Received decrypted content of length: %d.%n", decryptedResult.getPlainText().length);
-     * 
- * - * - * @param decryptParameters The parameters to use in the decryption operation. Microsoft recommends you not use CBC - * without first ensuring the integrity of the ciphertext using an HMAC, for example. - * See Timing vulnerabilities - * with CBC-mode symmetric decryption using padding for more information. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return The {@link DecryptResult} whose {@link DecryptResult#getPlainText() plain text} contains the decrypted - * content. - * - * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for decryption. - * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DecryptResult decrypt(DecryptParameters decryptParameters, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.decrypt(decryptParameters, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.decrypt(decryptParameters, context); - } - } - - /** - * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and - * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the - * signature from the digest. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Sings the digest prints out the signature details when a response has been received.

- * - * - *
-     * byte[] data = new byte[100];
-     * new Random(0x1234567L).nextBytes(data);
-     * MessageDigest md = MessageDigest.getInstance("SHA-256");
-     * md.update(data);
-     * byte[] digest = md.digest();
-     *
-     * SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, digest);
-     *
-     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length,
-     *     signResult.getAlgorithm());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param digest The content from which signature is to be created. - * - * @return A {@link SignResult} whose {@link SignResult#getSignature() signature} contains the created signature. - * - * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for signing. - * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) { - return sign(algorithm, digest, Context.NONE); - } - - /** - * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and - * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the - * signature from the digest. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Sings the digest prints out the signature details when a response has been received.

- * - * - *
-     * byte[] dataToVerify = new byte[100];
-     * new Random(0x1234567L).nextBytes(dataToVerify);
-     * MessageDigest myMessageDigest = MessageDigest.getInstance("SHA-256");
-     * myMessageDigest.update(dataToVerify);
-     * byte[] digestContent = myMessageDigest.digest();
-     *
-     * SignResult signResponse = cryptographyClient.sign(SignatureAlgorithm.ES256, digestContent,
-     *     new Context("key1", "value1"));
-     *
-     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResponse.getSignature().length,
-     *     signResponse.getAlgorithm());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param digest The content from which signature is to be created. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return A {@link SignResult} whose {@link SignResult#getSignature() signature} contains the created signature. - * - * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for signing. - * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.sign(algorithm, digest, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.sign(algorithm, digest, context); - } - } - - /** - * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric - * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation - * requires the {@code keys/verify} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the - * signature. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Verifies the signature against the specified digest prints out the verification details when a response has - * been received.

- * - * - *
-     * byte[] myData = new byte[100];
-     * new Random(0x1234567L).nextBytes(myData);
-     * MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
-     * messageDigest.update(myData);
-     * byte[] myDigest = messageDigest.digest();
-     *
-     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
-     * VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myDigest, signature);
-     *
-     * System.out.printf("Verification status: %s.%n", verifyResult.isValid());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param digest The content from which signature was created. - * @param signature The signature to be verified. - * - * @return A {@link VerifyResult} {@link VerifyResult#isValid() indicating the signature verification result}. - * - * @throws ResourceNotFoundException if the key cannot be found for verifying. - * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. - * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return verify(algorithm, digest, signature, Context.NONE); - } - - /** - * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric - * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation - * requires the {@code keys/verify} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the - * signature. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 ES384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Verifies the signature against the specified digest prints out the verification details when a response has - * been received.

- * - * - *
-     * byte[] dataBytes = new byte[100];
-     * new Random(0x1234567L).nextBytes(dataBytes);
-     * MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
-     * msgDigest.update(dataBytes);
-     * byte[] digestBytes = msgDigest.digest();
-     *
-     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
-     * VerifyResult verifyResponse = cryptographyClient.verify(SignatureAlgorithm.ES256, digestBytes, signatureBytes,
-     *     new Context("key1", "value1"));
-     *
-     * System.out.printf("Verification status: %s.%n", verifyResponse.isValid());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param digest The content from which signature was created. - * @param signature The signature to be verified. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return A {@link VerifyResult} {@link VerifyResult#isValid() indicating the signature verification result}. - * - * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for verifying. - * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.verify(algorithm, digest, signature, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.verify(algorithm, digest, signature, context); - } - } - - /** - * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both - * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local - * operations. - * - *

The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified - * key content. Possible values include: - * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128KW A128KW}, - * {@link EncryptionAlgorithm#A192KW A192KW} and {@link EncryptionAlgorithm#A256KW A256KW}.

- * - *

Code Samples

- *

Wraps the key content prints out the wrapped key details when a response has been received.

- * - * - *
-     * byte[] key = new byte[100];
-     * new Random(0x1234567L).nextBytes(key);
-     *
-     * WrapResult wrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key);
-     *
-     * System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n",
-     *     wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm());
-     * 
- * - * - * @param algorithm The encryption algorithm to use for wrapping the key. - * @param key The key content to be wrapped. - * - * @return The {@link WrapResult} whose {@link WrapResult#getEncryptedKey() encrypted key} contains the wrapped - * key result. - * - * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { - return wrapKey(algorithm, key, Context.NONE); - } - - /** - * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both - * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local - * operations. - * - *

The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified - * key content. Possible values include: - * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128KW A128KW}, - * {@link EncryptionAlgorithm#A192KW A192KW} and {@link EncryptionAlgorithm#A256KW A256KW}.

- * - *

Code Samples

- *

Wraps the key content prints out the wrapped key details when a response has been received.

- * - * - *
-     * byte[] keyToWrap = new byte[100];
-     * new Random(0x1234567L).nextBytes(keyToWrap);
-     *
-     * WrapResult keyWrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap,
-     *     new Context("key1", "value1"));
-     *
-     * System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n",
-     *     keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm());
-     * 
- * - * - * @param algorithm The encryption algorithm to use for wrapping the key. - * @param key The key content to be wrapped. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return The {@link WrapResult} whose {@link WrapResult#getEncryptedKey() encrypted key} contains the wrapped - * key result. - * - * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for encryption. - * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.wrapKey(algorithm, key, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.wrapKey(algorithm, key, context); - } - } - - /** - * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation - * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. - * This - * operation requires the {@code keys/unwrapKey} permission for non-local operations. - * - *

The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the - * specified encrypted key content. Possible values for asymmetric keys include: - * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link KeyWrapAlgorithm#A128KW A128KW}, - * {@link KeyWrapAlgorithm#A192KW A192KW} and {@link KeyWrapAlgorithm#A256KW A256KW}.

- * - *

Code Samples

- *

Unwraps the key content prints out the unwrapped key details when a response has been received.

- * - * - *
-     * byte[] keyContent = new byte[100];
-     * new Random(0x1234567L).nextBytes(keyContent);
-     *
-     * WrapResult wrapKeyResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContent,
-     *     new Context("key1", "value1"));
-     * UnwrapResult unwrapResult = cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP,
-     *     wrapKeyResult.getEncryptedKey());
-     *
-     * System.out.printf("Received key of length %d", unwrapResult.getKey().length);
-     * 
- * - * - * @param algorithm The encryption algorithm to use for wrapping the key. - * @param encryptedKey The encrypted key content to unwrap. - * - * @return An {@link UnwrapResult} whose {@link UnwrapResult#getKey() decrypted key} contains the unwrapped key - * result. - * - * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for wrap operation. - * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { - return unwrapKey(algorithm, encryptedKey, Context.NONE); - } - - /** - * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation - * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. - * This - * operation requires the {@code keys/unwrapKey} permission for non-local operations. - * - *

The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the - * specified encrypted key content. Possible values for asymmetric keys include: - * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and - * {@link KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. - *

- * Possible values for symmetric keys include: {@link KeyWrapAlgorithm#A128KW A128KW}, - * {@link KeyWrapAlgorithm#A192KW A192KW} and {@link KeyWrapAlgorithm#A256KW A256KW}.

- * - *

Code Samples

- *

Unwraps the key content prints out the unwrapped key details when a response has been received.

- * - * - *
-     * byte[] keyContentToWrap = new byte[100];
-     * new Random(0x1234567L).nextBytes(keyContentToWrap);
-     * Context context = new Context("key1", "value1");
-     *
-     * WrapResult wrapKeyContentResult =
-     *     cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContentToWrap, context);
-     * UnwrapResult unwrapKeyResponse =
-     *     cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapKeyContentResult.getEncryptedKey(), context);
-     *
-     * System.out.printf("Received key of length %d", unwrapKeyResponse.getKey().length);
-     * 
- * - * - * @param algorithm The encryption algorithm to use for wrapping the key. - * @param encryptedKey The encrypted key content to unwrap. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return An {@link UnwrapResult} whose {@link UnwrapResult#getKey() decrypted key} contains the unwrapped key - * result. - * - * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. - * @throws ResourceNotFoundException If the key cannot be found for wrap operation. - * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.unwrapKey(algorithm, encryptedKey, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.unwrapKey(algorithm, encryptedKey, context); - } - } - - /** - * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric - * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. - * Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Signs the raw data prints out the signature details when a response has been received.

- * - * - *
-     * byte[] data = new byte[32];
-     * new Random(0x1234567L).nextBytes(data);
-     *
-     * SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, data);
-     *
-     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length,
-     *     signResult.getAlgorithm());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param data The content from which signature is to be created. - * - * @return A {@link SignResult} whose {@link SignResult#getSignature() signature} contains the created signature. - * - * @throws NullPointerException if {@code algorithm} or {@code data} is null. - * @throws ResourceNotFoundException if the key cannot be found for signing. - * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SignResult signData(SignatureAlgorithm algorithm, byte[] data) { - return signData(algorithm, data, Context.NONE); - } - - /** - * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric - * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. - * Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Signs the raw data prints out the signature details when a response has been received.

- * - * - *
-     * byte[] plainTextData = new byte[32];
-     * new Random(0x1234567L).nextBytes(plainTextData);
-     *
-     * SignResult signingResult = cryptographyClient.sign(SignatureAlgorithm.ES256, plainTextData);
-     *
-     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n",
-     *     signingResult.getSignature().length, new Context("key1", "value1"));
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param data The content from which signature is to be created. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return A {@link SignResult} whose {@link SignResult#getSignature() signature} contains the created signature. - * - * @throws NullPointerException if {@code algorithm} or {@code data} is null. - * @throws ResourceNotFoundException if the key cannot be found for signing. - * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.signData(algorithm, data, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.signData(algorithm, data, context); - } - } - - /** - * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric - * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. - * This operation requires the {@code keys/verify} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the - * signature. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Verifies the signature against the raw data prints out the verification details when a response has been - * received.

- * - * - *
-     * byte[] myData = new byte[32];
-     * new Random(0x1234567L).nextBytes(myData);
-     *
-     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
-     * VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myData, signature);
-     *
-     * System.out.printf("Verification status: %s.%n", verifyResult.isValid());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param data The raw content against which signature is to be verified. - * @param signature The signature to be verified. - * - * @return A {@link VerifyResult} {@link VerifyResult#isValid() indicating the signature verification result}. - * - * @throws ResourceNotFoundException if the key cannot be found for verifying. - * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. - * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { - return verifyData(algorithm, data, signature, Context.NONE); - } - - /** - * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric - * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. - * This operation requires the {@code keys/verify} permission for non-local operations. - * - *

The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the - * signature. Possible values include: - * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, - * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES256K}, - * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, - * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, - * {@link SignatureAlgorithm#RS384 RS384}, and {@link SignatureAlgorithm#RS512 RS512}.

- * - *

Code Samples

- *

Verifies the signature against the raw data prints out the verification details when a response has been - * received.

- * - * - *
-     * byte[] dataToVerify = new byte[32];
-     * new Random(0x1234567L).nextBytes(dataToVerify);
-     *
-     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
-     * VerifyResult verificationResult = cryptographyClient.verify(SignatureAlgorithm.ES256, dataToVerify,
-     *     mySignature, new Context("key1", "value1"));
-     *
-     * System.out.printf("Verification status: %s.%n", verificationResult.isValid());
-     * 
- * - * - * @param algorithm The algorithm to use for signing. - * @param data The raw content against which signature is to be verified. - * @param signature The signature to be verified. - * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. - * - * @return A {@link VerifyResult} {@link VerifyResult#isValid() indicating the signature verification result}. - * - * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. - * @throws ResourceNotFoundException if the key cannot be found for verifying. - * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { - if (isLocalClientAvailable()) { - try { - return localKeyCryptographyClient.verifyData(algorithm, data, signature, context); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } else { - return implClient.verifyData(algorithm, data, signature, context); - } - } - - String getVaultUrl() { - return implClient.getVaultUrl(); - } - - private boolean isLocalClientAvailable() { - if (!skipLocalClientCreation && localKeyCryptographyClient == null) { - try { - localKeyCryptographyClient = retrieveJwkAndCreateLocalClient(implClient); - } catch (Throwable t) { - if (isThrowableRetryable(t)) { - LOGGER.log(LogLevel.VERBOSE, () -> "Could not set up local cryptography for this operation. " - + "Defaulting to service-side cryptography.", t); - } else { - skipLocalClientCreation = true; - - LOGGER.log(LogLevel.VERBOSE, () -> "Could not set up local cryptography. Defaulting to " - + "service-side cryptography for all operations.", t); - } - } - } - - return localKeyCryptographyClient != null; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java deleted file mode 100644 index 5f7a136fbb3b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java +++ /dev/null @@ -1,593 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeader; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.TracingOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.tracing.Tracer; -import com.azure.core.util.tracing.TracerProvider; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.keys.models.JsonWebKey; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the - * {@link CryptographyAsyncClient} and {@link CryptographyClient}, by calling - * {@link CryptographyClientBuilder#buildAsyncClient()} and {@link CryptographyClientBuilder#buildClient()} respectively - * It constructs an instance of the desired client. - * - *

The minimal configuration options required by {@link CryptographyClientBuilder cryptographyClientBuilder} to build - * a {@link CryptographyAsyncClient} or a {@link CryptographyClient} are a {@link TokenCredential credential} and either - * a {@link JsonWebKey JSON Web Key} or a {@code Azure Key Vault key identifier}.

- * - * - *
- * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
- *     .keyIdentifier("<your-key-id>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
- * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
- *     .jsonWebKey(jsonWebKey)
- *     .buildAsyncClient();
- * 
- * - * - *

When a {@link CryptographyAsyncClient} or {@link CryptographyClient} gets created using a - * {@code Azure Key Vault key identifier}, the first time a cryptographic operation is attempted, the client will - * attempt to retrieve the key material from the service, cache it, and perform all future cryptographic operations - * locally, deferring to the service when that's not possible. If key retrieval and caching fails because of a - * non-retryable error, the client will not make any further attempts and will fall back to performing all cryptographic - * operations on the service side. Conversely, when a {@link CryptographyAsyncClient} or {@link CryptographyClient} gets - * created using a {@link JsonWebKey JSON Web Key}, all cryptographic operations will be performed locally.

- * - *

To ensure correct behavior when performing operations such as {@code Decrypt}, {@code Unwrap} and - * {@code Verify}, it is recommended to use a {@link CryptographyAsyncClient} or {@link CryptographyClient} created - * for the specific key version that was used for the corresponding inverse operation: {@code Encrypt}, - * {@code Wrap}, or {@code Sign}, respectively.

- * - *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and a custom - * {@link HttpClient http client} can be optionally configured in the {@link CryptographyClientBuilder}.

- * - * - *
- * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
- *     .keyIdentifier("<your-key-id>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- *     .httpClient(HttpClient.createDefault())
- *     .buildAsyncClient();
- * 
- * - * - * @see CryptographyAsyncClient - * @see CryptographyClient - */ -@ServiceClientBuilder(serviceClients = CryptographyClient.class) -public final class CryptographyClientBuilder implements TokenCredentialTrait, - HttpTrait, ConfigurationTrait { - private static final ClientLogger LOGGER = new ClientLogger(CryptographyClientBuilder.class); - private static final String CLIENT_NAME; - private static final String CLIENT_VERSION; - - // Please see here - // for more information on Azure resource provider namespaces. - private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; - private final List perCallPolicies; - private final List perRetryPolicies; - - private ClientOptions clientOptions; - private Configuration configuration; - private CryptographyServiceVersion version; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions; - private HttpPipeline pipeline; - private JsonWebKey jsonWebKey; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private String keyId; - private TokenCredential credential; - private boolean isChallengeResourceVerificationDisabled = false; - private boolean isKeyCachingDisabled = false; - - static { - Map properties = CoreUtils.getProperties("azure-key-vault-keys.properties"); - CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); - CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); - } - - /** - * The constructor with defaults. - */ - public CryptographyClientBuilder() { - httpLogOptions = new HttpLogOptions(); - perCallPolicies = new ArrayList<>(); - perRetryPolicies = new ArrayList<>(); - } - - /** - * Creates a {@link CryptographyClient} based on options set in the builder. Every time {@code buildClient()} is - * called, a new instance of {@link CryptographyClient} is created. - * - *

If {@link CryptographyClientBuilder#jsonWebKey(JsonWebKey) jsonWebKey} is set, then all other builder - * settings are ignored.

- * - *

If {@link CryptographyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link CryptographyClientBuilder#keyIdentifier(String) jsonWebKey identifier} are used to create the - * {@link CryptographyClient client}. All other builder settings are ignored. If {@code pipeline} is not set, - * then an {@link CryptographyClientBuilder#credential(TokenCredential) Azure Key Vault credential} and - * {@link CryptographyClientBuilder#keyIdentifier(String) JSON Web Key identifier} are required to build the - * {@link CryptographyClient client}.

- * - * @return A {@link CryptographyClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link CryptographyClientBuilder#credential(TokenCredential)} is {@code null} or - * {@link CryptographyClientBuilder#keyIdentifier(String)} is empty or {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public CryptographyClient buildClient() { - if (jsonWebKey == null) { - if (CoreUtils.isNullOrEmpty(keyId)) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "An Azure Key Vault key identifier is required to build the cryptography client if a JSON Web Key" - + " is not provided.")); - } - - CryptographyServiceVersion serviceVersion - = version != null ? version : CryptographyServiceVersion.getLatest(); - - if (pipeline != null) { - return new CryptographyClient(keyId, pipeline, serviceVersion, isKeyCachingDisabled); - } - - if (credential == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "Azure Key Vault credentials are required to build the cryptography client if a JSON Web Key is not" - + " provided.")); - } - - HttpPipeline pipeline = setupPipeline(); - - return new CryptographyClient(keyId, pipeline, serviceVersion, isKeyCachingDisabled); - } else { - if (isKeyCachingDisabled) { - throw LOGGER.logExceptionAsError( - new IllegalStateException("Key caching cannot be disabled when using a JSON Web Key.")); - } - - return new CryptographyClient(jsonWebKey); - } - } - - /** - * Creates a {@link CryptographyAsyncClient} based on options set in the builder. Every time - * {@link #buildAsyncClient()} is called, a new instance of {@link CryptographyAsyncClient} is created. - * - *

If {@link CryptographyClientBuilder#jsonWebKey(JsonWebKey) jsonWebKey} is set, then all other builder - * settings are ignored.

- * - *

If {@link CryptographyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link CryptographyClientBuilder#keyIdentifier(String) jsonWebKey identifier}) are used to create the - * {@link CryptographyAsyncClient async client}. All other builder settings are ignored. If {@code pipeline} is - * not set, then an {@link CryptographyClientBuilder#credential(TokenCredential) Azure Key Vault credential} and - * {@link CryptographyClientBuilder#keyIdentifier(String) JSON Web Key identifier} are required to build the - * {@link CryptographyAsyncClient async client}.

- * - * @return A {@link CryptographyAsyncClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link CryptographyClientBuilder#credential(TokenCredential)} is {@code null} or - * {@link CryptographyClientBuilder#keyIdentifier(String)} is empty or {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public CryptographyAsyncClient buildAsyncClient() { - if (jsonWebKey == null) { - if (CoreUtils.isNullOrEmpty(keyId)) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "An Azure Key Vault key identifier is required to build the cryptography client if a JSON Web Key" - + " is not provided.")); - } - - CryptographyServiceVersion serviceVersion - = version != null ? version : CryptographyServiceVersion.getLatest(); - - if (pipeline != null) { - return new CryptographyAsyncClient(keyId, pipeline, serviceVersion, isKeyCachingDisabled); - } - - if (credential == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "Azure Key Vault credentials are required to build the cryptography client if a JSON Web Key is not" - + " provided.")); - } - - HttpPipeline pipeline = setupPipeline(); - - return new CryptographyAsyncClient(keyId, pipeline, serviceVersion, isKeyCachingDisabled); - } else { - if (isKeyCachingDisabled) { - throw LOGGER.logExceptionAsError( - new IllegalStateException("Key caching cannot be disabled when using a JSON Web Key.")); - } - - return new CryptographyAsyncClient(jsonWebKey); - } - } - - HttpPipeline setupPipeline() { - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; - - // Closest to API goes first, closest to wire goes last. - final List policies = new ArrayList<>(); - - httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - ClientOptions localClientOptions = clientOptions != null ? clientOptions : new ClientOptions(); - - policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), CLIENT_NAME, - CLIENT_VERSION, buildConfiguration)); - - List httpHeaderList = new ArrayList<>(); - localClientOptions.getHeaders() - .forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); - policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); - - // Add per call additional policies. - policies.addAll(perCallPolicies); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - // Add retry policy. - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - - policies.add(new KeyVaultCredentialPolicy(credential, isChallengeResourceVerificationDisabled)); - - // Add per retry additional policies. - policies.addAll(perRetryPolicies); - - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - - TracingOptions tracingOptions = localClientOptions.getTracingOptions(); - Tracer tracer = TracerProvider.getDefaultProvider() - .createTracer(CLIENT_NAME, CLIENT_VERSION, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - - return new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .tracer(tracer) - .clientOptions(localClientOptions) - .build(); - } - - TokenCredential getCredential() { - return credential; - } - - HttpPipeline getPipeline() { - return pipeline; - } - - CryptographyServiceVersion getServiceVersion() { - return version; - } - - /** - * Sets the Azure Key Vault key identifier of the JSON Web Key to be used for cryptography operations. You should - * validate that this URL references a valid Key Vault or Managed HSM resource. Refer to the following - * documentation for details. - * - *

To ensure correct behavior when performing operations such as {@code Decrypt}, {@code Unwrap} and - * {@code Verify}, it is recommended to use a {@link CryptographyAsyncClient} or {@link CryptographyClient} created - * for the specific key version that was used for the corresponding inverse operation: {@code Encrypt} - * {@code Wrap}, or {@code Sign}, respectively.

- * - * @param keyId The Azure Key Vault key identifier of the JSON Web Key stored in the key vault. - * - * @return The updated {@link CryptographyClientBuilder} object. - * - * @throws NullPointerException If {@code keyId} is {@code null}. - */ - public CryptographyClientBuilder keyIdentifier(String keyId) { - if (keyId == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'keyId' cannot be null.")); - } - - this.keyId = keyId; - - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link CryptographyClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public CryptographyClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - this.credential = credential; - - return this; - } - - /** - * Sets the {@link JsonWebKey} to be used for local cryptography operations. - * - *

If {@code jsonWebKey} is provided, then all other builder settings are ignored.

- * - * @param jsonWebKey The JSON Web Key to be used for local cryptography operations. - * - * @return The updated {@link CryptographyClientBuilder} object. - * - * @throws NullPointerException If {@code jsonWebKey} is {@code null}. - */ - public CryptographyClientBuilder jsonWebKey(JsonWebKey jsonWebKey) { - if (jsonWebKey == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'jsonWebKey' must not be null.")); - } - - this.jsonWebKey = jsonWebKey; - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated {@link CryptographyClientBuilder} object. - */ - @Override - public CryptographyClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated {@link CryptographyClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public CryptographyClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated {@link CryptographyClientBuilder} object. - */ - @Override - public CryptographyClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * The {@link #keyIdentifier(String) JSON Web Key identifier} is not ignored when - * {@code pipeline} is set. - * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated {@link CryptographyClientBuilder} object. - */ - @Override - public CryptographyClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - * - * The default configuration store is a clone of the - * {@link Configuration#getGlobalConfiguration() global configuration store}, use {@link Configuration#NONE} to - * bypass using configuration settings during construction. - * - * @param configuration The configuration store used to get configuration details. - * - * @return The updated {@link CryptographyClientBuilder} object. - */ - @Override - public CryptographyClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - - return this; - } - - /** - * Sets the {@link CryptographyServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. - * - * @return The updated {@link CryptographyClientBuilder} object. - */ - public CryptographyClientBuilder serviceVersion(CryptographyServiceVersion version) { - this.version = version; - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in - * the pipeline, if not provided. - * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy User's {@link RetryPolicy} applied to each request. - * - * @return The updated {@link CryptographyClientBuilder} object. - */ - public CryptographyClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated {@link CryptographyClientBuilder} object. - */ - @Override - public CryptographyClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @see HttpClientOptions - * @return The updated {@link CryptographyClientBuilder} object. - */ - @Override - public CryptographyClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault or Managed HSM domain. This - * verification is performed by default. - * - * @return The updated {@link CryptographyClientBuilder} object. - */ - public CryptographyClientBuilder disableChallengeResourceVerification() { - this.isChallengeResourceVerificationDisabled = true; - - return this; - } - - /** - * Disables local key caching and defers all cryptographic operations to the service. - * - *

This method will have no effect if used in conjunction with the - * {@link CryptographyClientBuilder#jsonWebKey(JsonWebKey)} method.

- * - * @return The updated {@link CryptographyClientBuilder} object. - */ - public CryptographyClientBuilder disableKeyCaching() { - this.isKeyCachingDisabled = true; - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java deleted file mode 100644 index 728b1b316463..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.util.ServiceVersion; - -/** - * The versions of Azure Key Vault Cryptography supported by this client library. - */ -public enum CryptographyServiceVersion implements ServiceVersion { - /** - * Service version {@code 7.0}. - */ - V7_0("7.0"), - - /** - * Service version {@code 7.1}. - */ - V7_1("7.1"), - - /** - * Service version {@code 7.2}. - */ - V7_2("7.2"), - - /** - * Service version {@code 7.3}. - */ - V7_3("7.3"), - - /** - * Service version {@code 7.4-preview.1}. - */ - V7_4("7.4"), - - /** - * Service version {@code 7.5}. - */ - V7_5("7.5"), - - /** - * Service version {@code 7.6-preview.1}. - */ - V7_6_PREVIEW_1("7.6-preview.1"); - - private final String version; - - CryptographyServiceVersion(String version) { - this.version = version; - } - - /** - * {@inheritDoc} - */ - @Override - public String getVersion() { - return this.version; - } - - /** - * Gets the latest service version supported by this client library - * - * @return the latest {@link CryptographyServiceVersion} - */ - public static CryptographyServiceVersion getLatest() { - return V7_6_PREVIEW_1; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java deleted file mode 100644 index eda9a075eb15..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.cryptography.AsyncKeyEncryptionKey; -import com.azure.core.http.HttpPipeline; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import reactor.core.publisher.Mono; - -import static com.azure.core.util.FluxUtil.monoError; - -/** - * A key client which is used to asynchronously wrap or unwrap another key. - * - *

When a {@link KeyEncryptionKeyAsyncClient} gets created using a {@code Azure Key Vault key identifier}, the first - * time a cryptographic operation is attempted, the client will attempt to retrieve the key material from the service, - * cache it, and perform all future cryptographic operations locally, deferring to the service when that's not possible. - * If key retrieval and caching fails because of a non-retryable error, the client will not make any further attempts - * and will fall back to performing all cryptographic operations on the service side. Conversely, when a - * {@link KeyEncryptionKeyAsyncClient} created using a {@link JsonWebKey JSON Web Key}, all cryptographic operations - * will be performed locally.

- */ -@ServiceClient(builder = KeyEncryptionKeyClientBuilder.class, isAsync = true) -public final class KeyEncryptionKeyAsyncClient extends CryptographyAsyncClient implements AsyncKeyEncryptionKey { - private static final ClientLogger LOGGER = new ClientLogger(KeyEncryptionKeyAsyncClient.class); - - /** - * Creates a {@link KeyEncryptionKeyAsyncClient} that uses {@code pipeline} to service requests. - * - * @param keyId The identifier of the key to use for cryptography operations. - * @param pipeline The {@link HttpPipeline} that the HTTP requests and responses flow through. - * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. - * @param disableKeyCaching Indicates if local key caching should be disabled and all cryptographic operations - * deferred to the service. - */ - KeyEncryptionKeyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version, - boolean disableKeyCaching) { - super(keyId, pipeline, version, disableKeyCaching); - } - - /** - * Creates a {@link KeyEncryptionKeyAsyncClient} that uses {@code pipeline} to service requests. - * - * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. - */ - KeyEncryptionKeyAsyncClient(JsonWebKey jsonWebKey) { - super(jsonWebKey); - } - - /** - * Get the identifier of the key to use for cryptography operations. - * - * @return A {@link Mono} containing the key identifier. - */ - @Override - public Mono getKeyId() { - return Mono.defer(() -> Mono.just(this.keyId)); - } - - /** - * {@inheritDoc} - */ - @Override - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono wrapKey(String algorithm, byte[] key) { - try { - KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.fromString(algorithm); - - return wrapKey(wrapAlgorithm, key).flatMap(keyWrapResult -> Mono.just(keyWrapResult.getEncryptedKey())); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * {@inheritDoc} - */ - @Override - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono unwrapKey(String algorithm, byte[] encryptedKey) { - try { - KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.fromString(algorithm); - - return unwrapKey(wrapAlgorithm, encryptedKey) - .flatMap(keyUnwrapResult -> Mono.just(keyUnwrapResult.getKey())); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java deleted file mode 100644 index 30c48f913cb5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.cryptography.KeyEncryptionKey; -import com.azure.core.http.HttpPipeline; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.models.JsonWebKey; - -/** - * A key client which is used to synchronously wrap or unwrap another key. - * - *

When a {@link KeyEncryptionKeyClient} gets created using a {@code Azure Key Vault key identifier}, the first time - * a cryptographic operation is attempted, the client will attempt to retrieve the key material from the service, cache - * it, and perform all future cryptographic operations locally, deferring to the service when that's not possible. If - * key retrieval and caching fails because of a non-retryable error, the client will not make any further attempts and - * will fall back to performing all cryptographic operations on the service side. Conversely, when a - * {@link KeyEncryptionKeyClient} created using a {@link JsonWebKey JSON Web Key}, all cryptographic operations will be - * performed locally.

- */ -@ServiceClient(builder = KeyEncryptionKeyClientBuilder.class) -public final class KeyEncryptionKeyClient extends CryptographyClient implements KeyEncryptionKey { - - /** - * Creates a {@link KeyEncryptionKeyClient} that uses a given {@link HttpPipeline pipeline} to service requests. - * - * @param keyId The identifier of the key to use for cryptography operations. - * @param pipeline The {@link HttpPipeline} that the HTTP requests and responses flow through. - * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. - * @param disableKeyCaching Indicates if local key caching should be disabled and all cryptographic operations - * deferred to the service. - */ - KeyEncryptionKeyClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version, - boolean disableKeyCaching) { - super(keyId, pipeline, version, disableKeyCaching); - } - - /** - * Creates a {@link KeyEncryptionKeyClient} that uses {@code pipeline} to service requests. - * - * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. - */ - KeyEncryptionKeyClient(JsonWebKey jsonWebKey) { - super(jsonWebKey); - } - - /** - * Get the identifier of the key to use for cryptography operations. - * - * @return The key identifier. - */ - @Override - public String getKeyId() { - return this.keyId; - } - - /** - * {@inheritDoc} - */ - @Override - @ServiceMethod(returns = ReturnType.SINGLE) - public byte[] wrapKey(String algorithm, byte[] key) { - KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.fromString(algorithm); - - return wrapKey(wrapAlgorithm, key).getEncryptedKey(); - } - - /** - * {@inheritDoc} - */ - @Override - @ServiceMethod(returns = ReturnType.SINGLE) - public byte[] unwrapKey(String algorithm, byte[] encryptedKey) { - KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.fromString(algorithm); - - return unwrapKey(wrapAlgorithm, encryptedKey).getKey(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilder.java deleted file mode 100644 index 06d06107ec64..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilder.java +++ /dev/null @@ -1,480 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.cryptography.AsyncKeyEncryptionKey; -import com.azure.core.cryptography.AsyncKeyEncryptionKeyResolver; -import com.azure.core.cryptography.KeyEncryptionKey; -import com.azure.core.cryptography.KeyEncryptionKeyResolver; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import reactor.core.publisher.Mono; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the - * {@link AsyncKeyEncryptionKey KeyEncryptionKey async client} and - * {@link KeyEncryptionKey KeyEncryptionKey sync client}, by calling - * {@link KeyEncryptionKeyClientBuilder#buildAsyncKeyEncryptionKey(String)} and - * {@link KeyEncryptionKeyClientBuilder#buildKeyEncryptionKey(String)} respectively. It constructs an instance of the - * desired client. - * - *

The minimal configuration options required by {@link KeyEncryptionKeyClientBuilder} to build - * {@link AsyncKeyEncryptionKey} are {@link JsonWebKey jsonWebKey} or {@link String Azure Key Vault key identifier} - * and {@link TokenCredential credential}.

- * - *

When a {@link AsyncKeyEncryptionKey KeyEncryptionKey async client} or - * {@link KeyEncryptionKey KeyEncryptionKey sync client} gets created using a - * {@code Azure Key Vault key identifier}, the first time a cryptographic operation is attempted, the client will - * attempt to retrieve the key material from the service, cache it, and perform all future cryptographic operations - * locally, deferring to the service when that's not possible. If key retrieval and caching fails because of a - * non-retryable error, the client will not make any further attempts and will fall back to performing all cryptographic - * operations on the service side. Conversely, when a {@link AsyncKeyEncryptionKey KeyEncryptionKey async client} or - * {@link KeyEncryptionKey KeyEncryptionKey sync client} gets created using a {@link JsonWebKey JSON Web Key}, all - * cryptographic operations will be performed locally.

- * - *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom - * {@link HttpClient http client} can be optionally configured in the {@link KeyEncryptionKeyClientBuilder}.

- * - *

Alternatively, a custom {@link HttpPipeline http pipeline} with custom {@link HttpPipelinePolicy} policies - * can be specified. It provides finer control over the construction of {@link AsyncKeyEncryptionKey} and - * {@link KeyEncryptionKey}

- * - *

The minimal configuration options required by {@link KeyEncryptionKeyClientBuilder keyEncryptionKeyClientBuilder} - * to build {@link KeyEncryptionKey} are {@link JsonWebKey jsonWebKey} or - * {@link String Azure Key Vault key identifier} and {@link TokenCredential credential}.

- * - * @see KeyEncryptionKeyAsyncClient - * @see KeyEncryptionKeyClient - */ -@ServiceClientBuilder(serviceClients = { KeyEncryptionKeyClient.class, KeyEncryptionKeyAsyncClient.class }) -public final class KeyEncryptionKeyClientBuilder implements KeyEncryptionKeyResolver, AsyncKeyEncryptionKeyResolver, - TokenCredentialTrait, HttpTrait, - ConfigurationTrait { - private static final ClientLogger LOGGER = new ClientLogger(KeyEncryptionKeyClientBuilder.class); - - private final CryptographyClientBuilder builder; - private boolean isKeyCachingDisabled = false; - - /** - * The constructor with defaults. - */ - public KeyEncryptionKeyClientBuilder() { - builder = new CryptographyClientBuilder(); - } - - /** - * Creates a {@link KeyEncryptionKey} based on options set in the builder. Every time - * {@code buildKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKey} is created. - * - *

If {@link KeyEncryptionKeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} - * and {@code keyId} are used to create the {@link KeyEncryptionKeyClient client}. All other builder settings are - * ignored. If {@code pipeline} is not set, then an - * {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential) Azure Key Vault credential} and {@code keyId} - * are required to build the {@link KeyEncryptionKeyClient client}.

- * - * @return A {@link KeyEncryptionKeyClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential)} or - * {@code keyId} have not been set. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - @Override - public KeyEncryptionKey buildKeyEncryptionKey(String keyId) { - builder.keyIdentifier(keyId); - - if (CoreUtils.isNullOrEmpty(keyId)) { - throw LOGGER.logExceptionAsError( - new IllegalStateException("An Azure Key Vault key identifier cannot be null and is required to build " - + "the key encryption key client.")); - } - - CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null - ? builder.getServiceVersion() - : CryptographyServiceVersion.getLatest(); - - if (builder.getPipeline() != null) { - return new KeyEncryptionKeyClient(keyId, builder.getPipeline(), serviceVersion, isKeyCachingDisabled); - } - - if (builder.getCredential() == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "Azure Key Vault credentials cannot be null and are required to build a key encryption key client.")); - } - - HttpPipeline pipeline = builder.setupPipeline(); - - return new KeyEncryptionKeyClient(keyId, pipeline, serviceVersion, isKeyCachingDisabled); - } - - /** - * Creates a local {@link KeyEncryptionKeyClient} for a given JSON Web Key. Every time - * {@code buildKeyEncryptionKey(JsonWebKey)} is called, a new instance of {@link KeyEncryptionKey} is created. - * For local clients, all other builder settings are ignored. - * - *

The {@code key} is required to build the {@link KeyEncryptionKeyClient client}.

- * - * @param key The {@link JsonWebKey} to be used for cryptography operations. - * - * @return A {@link KeyEncryptionKeyClient} with the options set from the builder. - * - * @throws IllegalStateException If {{@code key} is not set. - */ - public KeyEncryptionKey buildKeyEncryptionKey(JsonWebKey key) { - if (key == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "JSON Web Key cannot be null and is required to build a local key encryption key async client.")); - } else if (key.getId() == null) { - throw LOGGER - .logExceptionAsError(new IllegalArgumentException("JSON Web Key's id property is not configured.")); - } - - if (isKeyCachingDisabled) { - throw LOGGER.logExceptionAsError( - new IllegalStateException("Key caching cannot be disabled when using a JSON Web Key.")); - } - - return new KeyEncryptionKeyClient(key); - } - - /** - * Creates a {@link KeyEncryptionKeyAsyncClient} based on options set in the builder. Every time - * {@code buildAsyncKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKeyAsyncClient} is - * created. - * - *

If {@link KeyEncryptionKeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} - * and {@code keyId} are used to create the {@link KeyEncryptionKeyAsyncClient async client}. All other builder - * settings are ignored. If {@code pipeline} is not set, then an - * {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential) Azure Key Vault credentials} and - * {@code keyId} are required to build the {@link KeyEncryptionKeyAsyncClient async client}.

- * - * @param keyId The Azure Key Vault key identifier of the JSON Web Key stored in the key vault. You should validate - * that this URL references a valid Key Vault or Managed HSM resource. Refer to the following - * documentation for details. - * - * @return A {@link KeyEncryptionKeyAsyncClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential)} is - * {@code null} or {@code keyId} is empty or {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - @Override - public Mono buildAsyncKeyEncryptionKey(String keyId) { - builder.keyIdentifier(keyId); - - if (CoreUtils.isNullOrEmpty(keyId)) { - throw LOGGER.logExceptionAsError( - new IllegalStateException("An Azure Key Vault key identifier cannot be null and is required to build " - + "the key encryption key client.")); - } - - CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null - ? builder.getServiceVersion() - : CryptographyServiceVersion.getLatest(); - - if (builder.getPipeline() != null) { - return Mono.defer(() -> Mono.just( - new KeyEncryptionKeyAsyncClient(keyId, builder.getPipeline(), serviceVersion, isKeyCachingDisabled))); - } - - if (builder.getCredential() == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "Azure Key Vault credentials cannot be null and are required to build a key encryption key client.")); - } - - HttpPipeline pipeline = builder.setupPipeline(); - - return Mono.defer( - () -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, pipeline, serviceVersion, isKeyCachingDisabled))); - } - - /** - * Creates a local {@link KeyEncryptionKeyAsyncClient} based on options set in the builder. Every time - * {@code buildAsyncKeyEncryptionKey(String)} is called, a new instance of - * {@link KeyEncryptionKeyAsyncClient} is created. For local clients, all other builder settings are ignored. - * - *

The {@code key} is required to build the {@link KeyEncryptionKeyAsyncClient client}.

- * - * @param key The key to be used for cryptography operations. - * - * @return A {@link KeyEncryptionKeyAsyncClient} with the options set from the builder. - * - * @throws IllegalArgumentException If {@code key} has no id. - * @throws IllegalStateException If {@code key} is {@code null}. - */ - public Mono buildAsyncKeyEncryptionKey(JsonWebKey key) { - if (key == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "JSON Web Key cannot be null and is required to build a local key encryption key async client.")); - } else if (key.getId() == null) { - throw LOGGER - .logExceptionAsError(new IllegalArgumentException("JSON Web Key's id property is not configured.")); - } - - if (isKeyCachingDisabled) { - throw LOGGER.logExceptionAsError( - new IllegalStateException("Key caching cannot be disabled when using a JSON Web Key.")); - } - - return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(key))); - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - builder.credential(credential); - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - @Override - public KeyEncryptionKeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { - builder.httpLogOptions(logOptions); - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public KeyEncryptionKeyClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - builder.addPolicy(policy); - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - @Override - public KeyEncryptionKeyClientBuilder httpClient(HttpClient client) { - builder.httpClient(client); - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - @Override - public KeyEncryptionKeyClientBuilder pipeline(HttpPipeline pipeline) { - builder.pipeline(pipeline); - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - * - * The default configuration store is a clone of the - * {@link Configuration#getGlobalConfiguration() global configuration store}, use {@link Configuration#NONE} to - * bypass using configuration settings during construction. - * - * @param configuration The configuration store used to get configuration details. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - @Override - public KeyEncryptionKeyClientBuilder configuration(Configuration configuration) { - builder.configuration(configuration); - - return this; - } - - /** - * Sets the {@link CryptographyServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - public KeyEncryptionKeyClientBuilder serviceVersion(CryptographyServiceVersion version) { - builder.serviceVersion(version); - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in - * the pipeline, if not provided. - * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy User's retry policy applied to each request. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - public KeyEncryptionKeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { - builder.retryPolicy(retryPolicy); - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - @Override - public KeyEncryptionKeyClientBuilder retryOptions(RetryOptions retryOptions) { - builder.retryOptions(retryOptions); - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - * - * @see HttpClientOptions - */ - @Override - public KeyEncryptionKeyClientBuilder clientOptions(ClientOptions clientOptions) { - builder.clientOptions(clientOptions); - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault or Managed HSM domain. This - * verification is performed by default. - * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - public KeyEncryptionKeyClientBuilder disableChallengeResourceVerification() { - builder.disableChallengeResourceVerification(); - - return this; - } - - /** - * Disables local key caching and defers all cryptographic operations to the service. - * - *

This method will have no effect if - * {@link KeyEncryptionKeyClientBuilder#buildAsyncKeyEncryptionKey(JsonWebKey)} or - * {@link KeyEncryptionKeyClientBuilder#buildKeyEncryptionKey(JsonWebKey)} are used to create a client.

- * - * @return The updated {@link KeyEncryptionKeyClientBuilder} object. - */ - public KeyEncryptionKeyClientBuilder disableKeyCaching() { - this.isKeyCachingDisabled = true; - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Cbc.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Cbc.java deleted file mode 100644 index 2b0d05a6fcfd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Cbc.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes128Cbc extends AesCbc { - - private static final int KEY_SIZE = 128; - public static final String ALGORITHM_NAME = "A128CBC"; - - Aes128Cbc() { - super(ALGORITHM_NAME, KEY_SIZE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcHmacSha256.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcHmacSha256.java deleted file mode 100644 index 4e74ea3dcfa3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcHmacSha256.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes128CbcHmacSha256 extends AesCbcHmacSha2 { - - static final String ALGORITHM_NAME = "A128CBC-HS256"; - - Aes128CbcHmacSha256() { - super(ALGORITHM_NAME); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcPad.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcPad.java deleted file mode 100644 index dd73094922bc..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128CbcPad.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes128CbcPad extends AesCbcPad { - private static final int KEY_SIZE = 128; - public static final String ALGORITHM_NAME = "A128CBCPAD"; - - Aes128CbcPad() { - super(ALGORITHM_NAME, KEY_SIZE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Kw.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Kw.java deleted file mode 100644 index e51f562a7187..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes128Kw.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.util.Arrays; - -class Aes128Kw extends AesKw { - - public static final String ALGORITHM_NAME = "A128KW"; - - static final int KEY_SIZE_IN_BYTES = 128 >> 3; - - Aes128Kw() { - super(ALGORITHM_NAME); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - CryptographyUtils.validate(key, KEY_SIZE_IN_BYTES); - - return super.createEncryptor(Arrays.copyOfRange(key, 0, KEY_SIZE_IN_BYTES), iv, provider); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - CryptographyUtils.validate(key, KEY_SIZE_IN_BYTES); - - return super.createDecryptor(Arrays.copyOfRange(key, 0, KEY_SIZE_IN_BYTES), iv, provider); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Cbc.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Cbc.java deleted file mode 100644 index d3c2a77a3495..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Cbc.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes192Cbc extends AesCbc { - - private static final int KEY_SIZE = 192; - public static final String ALGORITHM_NAME = "A192CBC"; - - Aes192Cbc() { - super(ALGORITHM_NAME, KEY_SIZE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcHmacSha384.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcHmacSha384.java deleted file mode 100644 index 8a45b59077ca..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcHmacSha384.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes192CbcHmacSha384 extends AesCbcHmacSha2 { - - public static final String ALGORITHM_NAME = "A192CBC-HS384"; - - Aes192CbcHmacSha384() { - super(ALGORITHM_NAME); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcPad.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcPad.java deleted file mode 100644 index f94aa491d27e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192CbcPad.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes192CbcPad extends AesCbcPad { - private static final int KEY_SIZE = 192; - public static final String ALGORITHM_NAME = "A192CBCPAD"; - - Aes192CbcPad() { - super(ALGORITHM_NAME, KEY_SIZE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Kw.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Kw.java deleted file mode 100644 index 9cb9e2856494..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes192Kw.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.util.Arrays; - -class Aes192Kw extends AesKw { - - public static final String ALGORITHM_NAME = "A192KW"; - - static final int KEY_SIZE_IN_BYTES = 192 >> 3; - - Aes192Kw() { - super(ALGORITHM_NAME); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - CryptographyUtils.validate(key, KEY_SIZE_IN_BYTES); - - return super.createEncryptor(Arrays.copyOfRange(key, 0, KEY_SIZE_IN_BYTES), iv, provider); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - CryptographyUtils.validate(key, KEY_SIZE_IN_BYTES); - - return super.createDecryptor(Arrays.copyOfRange(key, 0, KEY_SIZE_IN_BYTES), iv, provider); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Cbc.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Cbc.java deleted file mode 100644 index ab3f26f2a127..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Cbc.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes256Cbc extends AesCbc { - - private static final int KEY_SIZE = 256; - public static final String ALGORITHM_NAME = "A256CBC"; - - Aes256Cbc() { - super(ALGORITHM_NAME, KEY_SIZE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcHmacSha512.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcHmacSha512.java deleted file mode 100644 index 114fc4e2a174..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcHmacSha512.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes256CbcHmacSha512 extends AesCbcHmacSha2 { - - public static final String ALGORITHM_NAME = "A256CBC-HS512"; - - Aes256CbcHmacSha512() { - super(ALGORITHM_NAME); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcPad.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcPad.java deleted file mode 100644 index 913b698f2872..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256CbcPad.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Aes256CbcPad extends AesCbcPad { - private static final int KEY_SIZE = 256; - public static final String ALGORITHM_NAME = "A256CBCPAD"; - - Aes256CbcPad() { - super(ALGORITHM_NAME, KEY_SIZE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Kw.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Kw.java deleted file mode 100644 index a1c1d72e1c41..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Aes256Kw.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.util.Arrays; - -class Aes256Kw extends AesKw { - - public static final String ALGORITHM_NAME = "A256KW"; - - static final int KEY_SIZE_IN_BYTES = 256 >> 3; - - Aes256Kw() { - super(ALGORITHM_NAME); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - CryptographyUtils.validate(key, KEY_SIZE_IN_BYTES); - - return super.createEncryptor(Arrays.copyOfRange(key, 0, KEY_SIZE_IN_BYTES), iv, provider); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - CryptographyUtils.validate(key, KEY_SIZE_IN_BYTES); - - return super.createDecryptor(Arrays.copyOfRange(key, 0, KEY_SIZE_IN_BYTES), iv, provider); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbc.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbc.java deleted file mode 100644 index 1f2756821fa1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbc.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.util.Arrays; - -abstract class AesCbc extends SymmetricEncryptionAlgorithm { - final int keySizeInBytes; - final int keySize; - - protected AesCbc(String name, int size) { - super(name); - - keySize = size; - keySizeInBytes = size >> 3; - } - - static class AesCbcEncryptor implements ICryptoTransform { - private final Cipher cipher; - - AesCbcEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - // Create the cipher using the Provider if specified - if (provider == null) { - cipher = Cipher.getInstance("AES/CBC/NoPadding"); - } else { - cipher = Cipher.getInstance("AES/CBC/NoPadding", provider); - } - - cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - } - - static class AesCbcDecryptor implements ICryptoTransform { - private final Cipher cipher; - - AesCbcDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - // Create the cipher using the Provider if specified - if (provider == null) { - cipher = Cipher.getInstance("AES/CBC/NoPadding"); - } else { - cipher = Cipher.getInstance("AES/CBC/NoPadding", provider); - } - - cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - - return createEncryptor(key, iv, additionalAuthenticatedData, null, null); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < keySizeInBytes) { - throw new InvalidKeyException("Key must be at least " + keySize + " bits in length."); - } - - return new AesCbcEncryptor(Arrays.copyOfRange(key, 0, keySizeInBytes), iv, provider); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - - return createDecryptor(key, iv, additionalAuthenticatedData, authenticationTag, null); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < keySizeInBytes) { - throw new InvalidKeyException("Key must be at least " + keySize + " bits in length."); - } - - return new AesCbcDecryptor(Arrays.copyOfRange(key, 0, keySizeInBytes), iv, provider); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcHmacSha2.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcHmacSha2.java deleted file mode 100644 index 09e5095e2efe..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcHmacSha2.java +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.logging.ClientLogger; -import reactor.util.function.Tuple3; -import reactor.util.function.Tuples; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.Mac; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.SecretKeySpec; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -abstract class AesCbcHmacSha2 extends SymmetricEncryptionAlgorithm { - private static final ClientLogger LOGGER = new ClientLogger(AesCbcHmacSha2.class); - private static final long BYTE_TO_BITS = 8L; - - abstract static class AbstractAesCbcHmacSha2CryptoTransform implements IAuthenticatedCryptoTransform { - byte[] tag; - final byte[] aadLength; - final Mac hmac; - final byte[] hmacKey; - final ICryptoTransform inner; - - AbstractAesCbcHmacSha2CryptoTransform(String name, byte[] keyMaterial, byte[] initializationVector, - byte[] authenticationData, ICryptoTransform.Factory factory) throws InvalidKeyException, - NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException { - Tuple3 parameters = getAlgorithmParameters(name, keyMaterial); - inner = factory.create(parameters.getT1()); - hmacKey = parameters.getT2(); - hmac = parameters.getT3(); - aadLength = toBigEndian(authenticationData.length * BYTE_TO_BITS); - hmac.update(authenticationData); - hmac.update(initializationVector); - } - - @Override - public byte[] getTag() { - return tag; - } - - private byte[] toBigEndian(long i) { - byte[] shortRepresentation = BigInteger.valueOf(i).toByteArray(); - byte[] longRepresentation = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; - - System.arraycopy(shortRepresentation, 0, longRepresentation, - longRepresentation.length - shortRepresentation.length, shortRepresentation.length); - - return longRepresentation; - } - - private Tuple3 getAlgorithmParameters(String algorithm, byte[] key) - throws InvalidKeyException, NoSuchAlgorithmException { - - byte[] aesKey; - byte[] hmacKey; - Mac hmac; - - if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.ALGORITHM_NAME)) { - if ((key.length << 3) < 256) { - throw new IllegalArgumentException( - String.format("%s key length in bits %d < 256", algorithm, key.length << 3)); - } - - hmacKey = new byte[128 >> 3]; - aesKey = new byte[128 >> 3]; - - // The HMAC key precedes the AES key - System.arraycopy(key, 0, hmacKey, 0, 128 >> 3); - System.arraycopy(key, 128 >> 3, aesKey, 0, 128 >> 3); - - hmac = Mac.getInstance("HmacSHA256"); - hmac.init(new SecretKeySpec(hmacKey, "HmacSHA256")); - - } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.ALGORITHM_NAME)) { - - if ((key.length << 3) < 384) { - throw new IllegalArgumentException( - String.format("%s key length in bits %d < 384", algorithm, key.length << 3)); - } - - hmacKey = new byte[192 >> 3]; - aesKey = new byte[192 >> 3]; - - // The HMAC key precedes the AES key - System.arraycopy(key, 0, hmacKey, 0, 192 >> 3); - System.arraycopy(key, 192 >> 3, aesKey, 0, 192 >> 3); - - hmac = Mac.getInstance("HmacSHA384"); - hmac.init(new SecretKeySpec(hmacKey, "HmacSHA384")); - } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.ALGORITHM_NAME)) { - - if ((key.length << 3) < 512) { - throw new IllegalArgumentException( - String.format("%s key length in bits %d < 512", algorithm, key.length << 3)); - } - - hmacKey = new byte[256 >> 3]; - aesKey = new byte[256 >> 3]; - - // The HMAC key precedes the AES key - System.arraycopy(key, 0, hmacKey, 0, 256 >> 3); - System.arraycopy(key, 256 >> 3, aesKey, 0, 256 >> 3); - - hmac = Mac.getInstance("HmacSHA512"); - hmac.init(new SecretKeySpec(hmacKey, "HmacSHA512")); - } else { - throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm)); - } - - return Tuples.of(aesKey, hmacKey, hmac); - } - } - - static class AesCbcHmacSha2Decryptor extends AbstractAesCbcHmacSha2CryptoTransform { - private static final ClientLogger LOGGER = new ClientLogger(AesCbcHmacSha2Decryptor.class); - - AesCbcHmacSha2Decryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, byte[] authenticationTag, - Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - super(name, key, iv, authenticationData, aesKey -> new AesCbc.AesCbcDecryptor(aesKey, iv, provider)); - // Save the tag - tag = authenticationTag; - } - - @Override - public byte[] doFinal(byte[] input) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { - - // Add the cipher text to the running hash - hmac.update(input); - - // Add the associated_data_length bytes to the hash - byte[] hash = hmac.doFinal(aadLength); - - // Compute the new tag - byte[] tag = new byte[hmacKey.length]; - System.arraycopy(hash, 0, tag, 0, hmacKey.length); - - // Check the tag before performing the final decrypt - if (!CryptographyUtils.sequenceEqualConstantTime(tag, tag)) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("Data is not authentic")); - } - - return inner.doFinal(input); - } - - } - - static class AesCbcHmacSha2Encryptor extends AbstractAesCbcHmacSha2CryptoTransform { - - AesCbcHmacSha2Encryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - super(name, key, iv, authenticationData, aesKey -> new AesCbc.AesCbcEncryptor(aesKey, iv, provider)); - } - - @Override - public byte[] doFinal(byte[] input) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { - - // Encrypt the block - byte[] output = inner.doFinal(input); - - // Add the cipher text to the running hash - hmac.update(output); - - // Add the associated_data_length bytes to the hash - byte[] hash = hmac.doFinal(aadLength); - - // Compute the tag - tag = new byte[hmacKey.length]; - System.arraycopy(hash, 0, tag, 0, tag.length); - - return output; - } - } - - protected AesCbcHmacSha2(String name) { - super(name); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - - return createDecryptor(key, iv, additionalAuthenticatedData, authenticationTag, null); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException { - if (key == null) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("No key material")); - } - - if (iv == null) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("No initialization vector")); - } - - if (additionalAuthenticatedData == null) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("No authentication data")); - } - - if (authenticationTag == null) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("No authentication tag")); - } - - // Create the Decryptor - return new AesCbcHmacSha2Decryptor(getName(), key, iv, additionalAuthenticatedData, authenticationTag, - provider); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - - return createEncryptor(key, iv, additionalAuthenticatedData, null, null); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("No key material")); - } - - if (iv == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("No initialization vector")); - } - - if (additionalAuthenticatedData == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("No authentication data")); - } - - // Create the Encryptor - return new AesCbcHmacSha2Encryptor(getName(), key, iv, additionalAuthenticatedData, provider); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcPad.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcPad.java deleted file mode 100644 index 7863da30fe5c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesCbcPad.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.util.Arrays; - -abstract class AesCbcPad extends SymmetricEncryptionAlgorithm { - final int keySizeInBytes; - final int keySize; - - protected AesCbcPad(String name, int size) { - super(name); - - keySize = size; - keySizeInBytes = size >> 3; - } - - static class AesCbcPadEncryptor implements ICryptoTransform { - private final Cipher cipher; - - AesCbcPadEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - // Create the cipher using the Provider if specified - if (provider == null) { - cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - } else { - cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", provider); - } - - cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - } - - static class AesCbcPadDecryptor implements ICryptoTransform { - private final Cipher cipher; - - AesCbcPadDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - // Create the cipher using the Provider if specified - if (provider == null) { - cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - } else { - cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", provider); - } - - cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - - return createEncryptor(key, iv, additionalAuthenticatedData, null, null); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < keySizeInBytes) { - throw new InvalidKeyException("key must be at least " + keySize + " bits in length"); - } - - return new AesCbcPadEncryptor(Arrays.copyOfRange(key, 0, keySizeInBytes), iv, provider); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException { - - return createDecryptor(key, iv, additionalAuthenticatedData, authenticationTag, null); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < keySizeInBytes) { - throw new InvalidKeyException("key must be at least " + keySize + " bits in length"); - } - - return new AesCbcPadDecryptor(Arrays.copyOfRange(key, 0, keySizeInBytes), iv, provider); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKeyCryptographyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKeyCryptographyClient.java deleted file mode 100644 index a1f880b9e18b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKeyCryptographyClient.java +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.Context; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyOperation; -import reactor.core.publisher.Mono; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Objects; - -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.verifyKeyPermissions; - -class AesKeyCryptographyClient extends LocalKeyCryptographyClient { - private final byte[] aesKey; - - static final int AES_BLOCK_SIZE = 16; - - AesKeyCryptographyClient(JsonWebKey jsonWebKey, CryptographyClientImpl implClient) { - super(jsonWebKey, implClient); - - aesKey = jsonWebKey.toAes().getEncoded(); - - if (aesKey == null || aesKey.length == 0) { - throw new IllegalArgumentException("The provided JSON Web Key cannot be null or empty."); - } - } - - @Override - public Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - try { - return encryptInternalAsync(algorithm, plaintext, null, null, context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - try { - return encryptInternal(algorithm, plaintext, null, null, context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono encryptAsync(EncryptParameters encryptParameters, Context context) { - Objects.requireNonNull(encryptParameters, "Encrypt parameters cannot be null."); - - try { - return encryptInternalAsync(encryptParameters.getAlgorithm(), encryptParameters.getPlainText(), - encryptParameters.getIv(), encryptParameters.getAdditionalAuthenticatedData(), context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public EncryptResult encrypt(EncryptParameters encryptParameters, Context context) { - Objects.requireNonNull(encryptParameters, "Encrypt parameters cannot be null."); - - try { - return encryptInternal(encryptParameters.getAlgorithm(), encryptParameters.getPlainText(), - encryptParameters.getIv(), encryptParameters.getAdditionalAuthenticatedData(), context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private Mono encryptInternalAsync(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, - byte[] additionalAuthenticatedData, Context context) throws NoSuchAlgorithmException { - - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext cannot be null."); - - // Interpret the algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { - if (implClient != null) { - return implClient.encryptAsync(algorithm, plaintext, context); - } - - throw new NoSuchAlgorithmException(algorithm.toString()); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.ENCRYPT); - validateEncryptionAlgorithm(algorithm); - - SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; - - final byte[] finalIv; - - if (iv == null) { - if (isAes(algorithm)) { - try { - finalIv = generateIv(AES_BLOCK_SIZE); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Could not generate iv for this local operation.", e); - } - } else { - throw new IllegalArgumentException("Encryption algorithm provided is not supported: " + algorithm); - } - } else { - finalIv = iv; - } - - return Mono.fromCallable(() -> { - byte[] ciphertext - = symmetricEncryptionAlgorithm.createEncryptor(aesKey, finalIv, additionalAuthenticatedData, null) - .doFinal(plaintext); - - return new EncryptResult(ciphertext, algorithm, jsonWebKey.getId(), finalIv, null, - additionalAuthenticatedData); - }); - } - - private EncryptResult encryptInternal(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, - byte[] additionalAuthenticatedData, Context context) throws BadPaddingException, IllegalBlockSizeException, - InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext cannot be null."); - - // Interpret the algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { - if (implClient != null) { - return implClient.encrypt(algorithm, plaintext, context); - } - - throw new NoSuchAlgorithmException(algorithm.toString()); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.ENCRYPT); - validateEncryptionAlgorithm(algorithm); - - SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; - - if (iv == null) { - if (isAes(algorithm)) { - try { - iv = generateIv(AES_BLOCK_SIZE); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Could not generate iv for this local operation.", e); - } - } else { - throw new IllegalArgumentException("Encryption algorithm provided is not supported: " + algorithm); - } - } - - byte[] ciphertext = symmetricEncryptionAlgorithm.createEncryptor(aesKey, iv, additionalAuthenticatedData, null) - .doFinal(plaintext); - - return new EncryptResult(ciphertext, algorithm, jsonWebKey.getId(), iv, null, additionalAuthenticatedData); - } - - @Override - public Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - try { - return decryptInternalAsync(algorithm, ciphertext, null, null, null, context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - try { - return decryptInternal(algorithm, ciphertext, null, null, null, context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono decryptAsync(DecryptParameters decryptParameters, Context context) { - Objects.requireNonNull(decryptParameters, "Decrypt parameters cannot be null."); - - try { - return decryptInternalAsync(decryptParameters.getAlgorithm(), decryptParameters.getCipherText(), - decryptParameters.getIv(), decryptParameters.getAdditionalAuthenticatedData(), - decryptParameters.getAuthenticationTag(), context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public DecryptResult decrypt(DecryptParameters decryptParameters, Context context) { - Objects.requireNonNull(decryptParameters, "Decrypt parameters cannot be null."); - - try { - return decryptInternal(decryptParameters.getAlgorithm(), decryptParameters.getCipherText(), - decryptParameters.getIv(), decryptParameters.getAdditionalAuthenticatedData(), - decryptParameters.getAuthenticationTag(), context); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private Mono decryptInternalAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, - byte[] additionalAuthenticatedData, byte[] authenticationTag, Context context) throws NoSuchAlgorithmException { - - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Ciphertext cannot be null."); - - // Interpret the algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { - if (implClient != null) { - return implClient.decryptAsync(algorithm, ciphertext, context); - } - - throw new NoSuchAlgorithmException(algorithm.toString()); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.DECRYPT); - validateEncryptionAlgorithm(algorithm); - - SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; - - Objects.requireNonNull(iv, "'iv' cannot be null in local decryption operations."); - - return Mono.fromCallable(() -> { - byte[] plaintext = symmetricEncryptionAlgorithm - .createDecryptor(aesKey, iv, additionalAuthenticatedData, authenticationTag) - .doFinal(ciphertext); - - return new DecryptResult(plaintext, algorithm, jsonWebKey.getId()); - }); - } - - private DecryptResult decryptInternal(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, - byte[] additionalAuthenticatedData, byte[] authenticationTag, Context context) - throws BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, - NoSuchAlgorithmException, NoSuchPaddingException { - - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Ciphertext cannot be null."); - - // Interpret the algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { - if (implClient != null) { - return implClient.decrypt(algorithm, ciphertext, context); - } - - throw new NoSuchAlgorithmException(algorithm.toString()); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.DECRYPT); - validateEncryptionAlgorithm(algorithm); - - SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; - - Objects.requireNonNull(iv, "'iv' cannot be null in local decryption operations."); - - byte[] plaintext - = symmetricEncryptionAlgorithm.createDecryptor(aesKey, iv, additionalAuthenticatedData, authenticationTag) - .doFinal(ciphertext); - - return new DecryptResult(plaintext, algorithm, jsonWebKey.getId()); - } - - private static void validateEncryptionAlgorithm(EncryptionAlgorithm algorithm) { - if (isGcm(algorithm)) { - throw new UnsupportedOperationException("AES-GCM is not supported for local cryptography operations."); - } - - if (!isAes(algorithm)) { - throw new IllegalArgumentException("Encryption algorithm provided is not supported: " + algorithm); - } - } - - @Override - public Mono signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context) { - throw new UnsupportedOperationException("The sign operation not supported for OCT/symmetric keys."); - } - - @Override - public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { - throw new UnsupportedOperationException("The sign operation not supported for OCT/symmetric keys."); - } - - @Override - public Mono verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, - Context context) { - throw new UnsupportedOperationException("The verify operation is not supported for OCT/symmetric keys."); - } - - public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - throw new UnsupportedOperationException("The verify operation is not supported for OCT/symmetric keys."); - } - - @Override - public Mono wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(keyToWrap, "Key content to be wrapped cannot be null."); - - // Interpret the algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { - if (implClient != null) { - return implClient.wrapKeyAsync(algorithm, keyToWrap, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.WRAP_KEY); - - LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; - - return Mono.fromCallable(() -> { - byte[] encrypted = localKeyWrapAlgorithm.createEncryptor(aesKey, null, null).doFinal(keyToWrap); - - return new WrapResult(encrypted, algorithm, jsonWebKey.getId()); - }); - } - - @Override - public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(keyToWrap, "Key content to be wrapped cannot be null."); - - // Interpret the algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { - if (implClient != null) { - return implClient.wrapKey(algorithm, keyToWrap, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.WRAP_KEY); - - LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; - - ICryptoTransform transform; - - try { - transform = localKeyWrapAlgorithm.createEncryptor(aesKey, null, null); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - - byte[] encrypted; - - try { - encrypted = transform.doFinal(keyToWrap); - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException(e); - } - } - - return new WrapResult(encrypted, algorithm, jsonWebKey.getId()); - } - - @Override - public Mono unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { - if (implClient != null) { - return implClient.unwrapKeyAsync(algorithm, encryptedKey, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.UNWRAP_KEY); - - LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; - - return Mono.fromCallable(() -> { - byte[] decrypted = localKeyWrapAlgorithm.createDecryptor(aesKey, null, null).doFinal(encryptedKey); - - return new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()); - }); - } - - @Override - public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - - verifyKeyPermissions(jsonWebKey, KeyOperation.UNWRAP_KEY); - - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { - if (implClient != null) { - return implClient.unwrapKey(algorithm, encryptedKey, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.UNWRAP_KEY); - - LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; - - try { - byte[] decrypted = localKeyWrapAlgorithm.createDecryptor(aesKey, null, null).doFinal(encryptedKey); - - return new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context) { - return signAsync(algorithm, data, context); - } - - @Override - public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { - return sign(algorithm, data, context); - } - - @Override - public Mono verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, - Context context) { - return verifyAsync(algorithm, data, signature, context); - } - - public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { - return verify(algorithm, data, signature, context); - } - - private static byte[] generateIv(int sizeInBytes) throws NoSuchAlgorithmException { - SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG"); - byte[] iv = new byte[sizeInBytes]; - - randomSecureRandom.nextBytes(iv); - - return iv; - } - - private static boolean isAes(EncryptionAlgorithm encryptionAlgorithm) { - return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC - || encryptionAlgorithm == EncryptionAlgorithm.A192CBC - || encryptionAlgorithm == EncryptionAlgorithm.A256CBC - || encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD - || encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD - || encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD); - } - - private static boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) { - return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM - || encryptionAlgorithm == EncryptionAlgorithm.A192GCM - || encryptionAlgorithm == EncryptionAlgorithm.A256GCM); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKw.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKw.java deleted file mode 100644 index 240cb709e676..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AesKw.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.logging.ClientLogger; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -abstract class AesKw extends LocalKeyWrapAlgorithm { - private static final ClientLogger LOGGER = new ClientLogger(AesKw.class); - - static final int BLOCK_SIZE_IN_BITS = 64; - static final String CIPHER_NAME = "AESWrap"; - static final byte[] DEFAULT_IV = new byte[] { - (byte) 0xA6, - (byte) 0xA6, - (byte) 0xA6, - (byte) 0xA6, - (byte) 0xA6, - (byte) 0xA6, - (byte) 0xA6, - (byte) 0xA6 }; - - static class AesKwDecryptor implements ICryptoTransform { - final Cipher cipher; - - AesKwDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - if (provider == null) { - cipher = Cipher.getInstance(CIPHER_NAME); - } else { - cipher = Cipher.getInstance(CIPHER_NAME, provider); - } - - // The default provider does not support the specification of IV. This is guarded by the CreateEncrypter - // wrapper method and the iv parameter can be ignored when using the default provider. - if (provider == null) { - cipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(key, "AES")); - } else { - cipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); - } - } - - @Override - public byte[] doFinal(byte[] plaintext) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { - - return cipher.unwrap(plaintext, "AESWrap", Cipher.SECRET_KEY).getEncoded(); - } - - } - - static class AesKwEncryptor implements ICryptoTransform { - - final Cipher cipher; - - AesKwEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - if (provider == null) { - cipher = Cipher.getInstance(CIPHER_NAME); - } else { - cipher = Cipher.getInstance(CIPHER_NAME, provider); - } - - // The default provider does not support the specification of IV. This is guarded by the CreateEncrypter - // wrapper method and the iv parameter can be ignored when using the default provider. - if (provider == null) { - cipher.init(Cipher.WRAP_MODE, new SecretKeySpec(key, "AES")); - } else { - cipher.init(Cipher.WRAP_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); - } - } - - @Override - public byte[] doFinal(byte[] plaintext) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException { - - return cipher.wrap(new SecretKeySpec(plaintext, "AES")); - } - - } - - protected AesKw(String name) { - super(name); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, - InvalidKeyException, InvalidAlgorithmParameterException { - - return createEncryptor(key, null, null); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - return createEncryptor(key, null, provider); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - return createEncryptor(key, iv, null); - } - - @Override - public ICryptoTransform createEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - if (key == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("key")); - } - - if (key.length != 128 >> 3 && key.length != 192 >> 3 && key.length != 256 >> 3) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("key length must be 128, 192 or 256 bits")); - } - - if (iv != null) { - // iv length must be 64 bits - if (iv.length != BLOCK_SIZE_IN_BITS >> 3) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException(String.format("iv length must be %s bits", BLOCK_SIZE_IN_BITS))); - } - // iv cannot be specified with the default provider - if (provider == null) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("user specified iv is not supported with the default provider")); - } - } - - return new AesKwEncryptor(key, iv == null ? DEFAULT_IV : iv, provider); - - } - - @Override - public ICryptoTransform createDecryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, - InvalidKeyException, InvalidAlgorithmParameterException { - - return createDecryptor(key, null, null); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - return createDecryptor(key, null, provider); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - return createDecryptor(key, iv, null); - } - - @Override - public ICryptoTransform createDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { - - if (key == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("key")); - } - - if (key.length != 128 >> 3 && key.length != 192 >> 3 && key.length != 256 >> 3) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("key length must be 128, 192 or 256 bits")); - } - - if (iv != null) { - // iv length must be 64 bits - if (iv.length != BLOCK_SIZE_IN_BITS >> 3) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException(String.format("iv length must be %s bits", BLOCK_SIZE_IN_BITS))); - } - // iv cannot be specified with the default provider - if (provider == null) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("user specified iv is not supported with the default provider")); - } - } - - return new AesKwDecryptor(key, iv == null ? DEFAULT_IV : iv, provider); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Algorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Algorithm.java deleted file mode 100644 index 3ee8f76449fd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Algorithm.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.CoreUtils; - -/** - * Abstract base class for all Algorithm objects. - * - */ -abstract class Algorithm { - - private final String name; - - Algorithm(String name) { - if (CoreUtils.isNullOrEmpty(name) || name.trim().isEmpty()) { - throw new IllegalArgumentException("name"); - } - - this.name = name; - } - - /* - * Gets the name of the algorithm. - * - * @return The name of the algorithm. - */ - public String getName() { - return name; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AlgorithmResolver.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AlgorithmResolver.java deleted file mode 100644 index 67f759feecb7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AlgorithmResolver.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import java.util.HashMap; -import java.util.Map; - -final class AlgorithmResolver { - - static final AlgorithmResolver DEFAULT; - - static { - Map algorithms = new HashMap<>(); - algorithms.put(Aes128Cbc.ALGORITHM_NAME, new Aes128Cbc()); - algorithms.put(Aes192Cbc.ALGORITHM_NAME, new Aes192Cbc()); - algorithms.put(Aes256Cbc.ALGORITHM_NAME, new Aes256Cbc()); - - algorithms.put(Aes128CbcPad.ALGORITHM_NAME, new Aes128CbcPad()); - algorithms.put(Aes192CbcPad.ALGORITHM_NAME, new Aes192CbcPad()); - algorithms.put(Aes256CbcPad.ALGORITHM_NAME, new Aes256CbcPad()); - - algorithms.put(Aes128CbcHmacSha256.ALGORITHM_NAME, new Aes128CbcHmacSha256()); - algorithms.put(Aes192CbcHmacSha384.ALGORITHM_NAME, new Aes192CbcHmacSha384()); - algorithms.put(Aes256CbcHmacSha512.ALGORITHM_NAME, new Aes256CbcHmacSha512()); - - algorithms.put(Aes128Kw.ALGORITHM_NAME, new Aes128Kw()); - algorithms.put(Aes192Kw.ALGORITHM_NAME, new Aes192Kw()); - algorithms.put(Aes256Kw.ALGORITHM_NAME, new Aes256Kw()); - - algorithms.put(Rsa15.ALGORITHM_NAME, new Rsa15()); - algorithms.put(RsaOaep.ALGORITHM_NAME, new RsaOaep()); - - algorithms.put(Es256k.ALGORITHM_NAME, new Es256k()); - algorithms.put(Es256.ALGORITHM_NAME, new Es256()); - algorithms.put(Es384.ALGORITHM_NAME, new Es384()); - algorithms.put(Es512.ALGORITHM_NAME, new Es512()); - - DEFAULT = new AlgorithmResolver(algorithms); - } - - private final Map algorithms; - - private AlgorithmResolver(Map algorithms) { - this.algorithms = algorithms; - } - - /** - * Returns the implementation for an algorithm name. - * - * @param algorithmName The algorithm name. - * @return The implementation for the algorithm or null. - */ - public Algorithm get(String algorithmName) { - return algorithms.get(algorithmName); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Asn1DerSignatureEncoding.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Asn1DerSignatureEncoding.java deleted file mode 100644 index 13918d78ea3c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Asn1DerSignatureEncoding.java +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.cryptography.implementation; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.math.BigInteger; -import java.util.Arrays; - -final class Asn1DerSignatureEncoding { - // the EDCSA ASN.1 DER signature is in the format: - // 0x30 b1 0x02 b2 (vr) 0x02 b3 (vs) - // where: - // * b1 one or more bytes equal to the length, in bytes, of the remaining list of bytes (from the first 0x02 - // to the end of the encoding) - // * b2 one or more bytes equal to the length, in bytes, of (vr) - // * b3 one or more bytes equal to the length, in bytes, of (vs) - // (vr) is the signed big-endian encoding of the value "r", of minimal length - // (vs) is the signed big-endian encoding of the value "s", of minimal length - // - // * lengths which are less than 0x80 can be expressed in one byte. For lengths greater then 0x80 the first - // byte denotes the - // length in bytes of the length with the most significant bit masked off, i.e. 0x81 denotes the length is - // one byte long. - - private Asn1DerSignatureEncoding() { - - } - - static byte[] encode(byte[] signature, Ecdsa algorithm) { - int coordLength = algorithm.getCoordLength(); - - // verify that the signature is the correct length for the given algorithm - if (signature.length != (coordLength * 2)) { - throw new IllegalArgumentException("Invalid signature."); - } - - // r is the first half of the signature - BigInteger r = new BigInteger(1, Arrays.copyOfRange(signature, 0, signature.length / 2)); - - // s is the second half of the signature - BigInteger s = new BigInteger(1, Arrays.copyOfRange(signature, signature.length / 2, signature.length)); - - // vr and vs are the compacted ASN.1 integer encoding, same as BigInteger encoding - byte[] rfield = encodeIntField(r); - - byte[] sfield = encodeIntField(s); - - ByteArrayOutputStream asn1DerSignature = new ByteArrayOutputStream(); - - asn1DerSignature.write(0x30); - - // add the length of the fields - writeFieldLength(asn1DerSignature, rfield.length + sfield.length); - - // write the fields - asn1DerSignature.write(rfield, 0, rfield.length); - - asn1DerSignature.write(sfield, 0, sfield.length); - - return asn1DerSignature.toByteArray(); - } - - static byte[] decode(byte[] bytes, Ecdsa algorithm) { - int coordLength = algorithm.getCoordLength(); - - ByteArrayInputStream asn1DerSignature = new ByteArrayInputStream(bytes); - - // verify byte 0 is 0x30 - if (asn1DerSignature.read() != 0x30) { - throw new IllegalArgumentException("Invalid signature."); - } - - int objLen = readFieldLength(asn1DerSignature); - - // verify the object length is equal to the remaining length of the - // _asn1DerSignature - if (objLen != asn1DerSignature.available()) { - throw new IllegalArgumentException(String.format("Invalid signature; invalid field len %d", objLen)); - } - - byte[] rawSignature = new byte[coordLength * 2]; - - // decode the r field to the first half of _rawSignature - decodeIntField(asn1DerSignature, rawSignature, 0, coordLength); - - // decode the s field to the second half of _rawSignature - decodeIntField(asn1DerSignature, rawSignature, rawSignature.length / 2, coordLength); - - return rawSignature; - } - - static byte[] encodeIntField(BigInteger i) { - ByteArrayOutputStream field = new ByteArrayOutputStream(); - - field.write(0x02); - - // get this byte array for the asn1 encoded integer - byte[] vi = i.toByteArray(); - - // write the length of the field - writeFieldLength(field, vi.length); - - // write the field value - field.write(vi, 0, vi.length); - - return field.toByteArray(); - } - - static void writeFieldLength(ByteArrayOutputStream field, int len) { - // if the length of vi is less then 0x80 we can fit the length in one byte - if (len < 0x80) { - field.write(len); - } else { - // get the len as a byte array - byte[] blen = BigInteger.valueOf(len).toByteArray(); - - int lenlen = blen.length; - - // the byte array might have a leading zero byte if so we need to discard this - if (blen[0] == 0) { - lenlen--; - } - - // write the continuation byte containing the length length in bytes - field.write(0x80 | lenlen); - - // write the field lenth bytes - field.write(blen, blen.length - lenlen, lenlen); - } - } - - static void decodeIntField(ByteArrayInputStream bytes, byte[] dest, int index, int intlen) { - // verify the first byte of field is 0x02 - if (bytes.read() != 0x02) { - throw new IllegalArgumentException("Invalid signature."); - } - - //get the length of the field - int len = readFieldLength(bytes); - - // if the most significant bit of the raw int was set an extra zero byte will be prepended to - // the asn1der encoded value so len can have a max value of intlen + 1 - - // validate that len is within the max range and doesn't run past the end of bytes - if (len > intlen + 1 || len > bytes.available()) { - throw new IllegalArgumentException("Invalid signature."); - } - - // if len is greater than intlen increment _bytesRead and decrement len - if (len > intlen) { - bytes.skip(1); - len--; - } - - bytes.read(dest, index + (intlen - len), len); - } - - static int readFieldLength(ByteArrayInputStream bytes) { - int firstLenByte = bytes.read(); - - // if the high order bit of len is not set it is a single byte length so return - if ((firstLenByte & 0x80) == 0x00) { - return firstLenByte; - } - - // otherwise mask off the high order bit to get the number of bytes to read - int numLenBytes = firstLenByte ^ 0x80; - - // if the number of len bytes is greater than the remaining signature the signature is invalid - if (numLenBytes > bytes.available()) { - throw new IllegalArgumentException("Invalid signature."); - } - - byte[] lenBytes = new byte[numLenBytes]; - - bytes.read(lenBytes, 0, numLenBytes); - - BigInteger bigLen = new BigInteger(1, lenBytes); - - // for DSA signatures no feilds should be longer than can be expressed in an integer - // this means that the bitLength must be 31 or less to account for the leading zero of - // a positive integer - if (bigLen.bitLength() >= 31) { - throw new IllegalArgumentException("Invalid signature."); - } - - return bigLen.intValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricEncryptionAlgorithm.java deleted file mode 100644 index 44171beb1099..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricEncryptionAlgorithm.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -/** - * Abstract base class for all asymmetric encryption implementation. - * - */ -abstract class AsymmetricEncryptionAlgorithm extends LocalEncryptionAlgorithm { - - /** - * Constructor. - * - * @param name The name of the algorithm. - */ - protected AsymmetricEncryptionAlgorithm(String name) { - super(name); - } - - /** - * Creates a {@link ICryptoTransform} implementation for encryption that - * uses the specified {@link KeyPair} and the default {@link Provider} provider. - * - * @param keyPair The key pair to use. - * @return abstract {@link ICryptoTransform} - * @throws InvalidKeyException when key is not valid - * @throws NoSuchAlgorithmException if algorithm is not found - * @throws NoSuchPaddingException if padding is set wrong - */ - public abstract ICryptoTransform createEncryptor(KeyPair keyPair) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; - - /** - * Creates a {@link ICryptoTransform} implementation for encryption that - * uses the specified {@link KeyPair} and {@link Provider}. - * - * @param keyPair The key pair to use. - * @param provider The provider to use. - * @return abstract {@link ICryptoTransform} - * @throws InvalidKeyException when key is not valid - * @throws NoSuchAlgorithmException if algorithm is not found - * @throws NoSuchPaddingException if padding is set wrong - */ - public abstract ICryptoTransform createEncryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; - - /** - * Creates a {@link ICryptoTransform} implementation for decryption that - * uses the specified {@link KeyPair} and the default {@link Provider} provider. - * - * @param keyPair The key pair to use. - * @return abstract {@link ICryptoTransform} - * @throws InvalidKeyException when key is not valid - * @throws NoSuchAlgorithmException if algorithm is not found - * @throws NoSuchPaddingException if padding is set wrong - */ - public abstract ICryptoTransform createDecryptor(KeyPair keyPair) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; - - /** - * Creates a {@link ICryptoTransform} implementation for decryption that - * uses the specified {@link KeyPair} and {@link Provider}. - * - * @param keyPair The key pair to use. - * @param provider The provider to use. - * @return abstract {@link ICryptoTransform} - * @throws InvalidKeyException when key is not valid - * @throws NoSuchAlgorithmException if algorithm is not found - * @throws NoSuchPaddingException if padding is set wrong - */ - public abstract ICryptoTransform createDecryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricSignatureAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricSignatureAlgorithm.java deleted file mode 100644 index 6b20626a10ed..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/AsymmetricSignatureAlgorithm.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class AsymmetricSignatureAlgorithm extends LocalSignatureAlgorithm { - - protected AsymmetricSignatureAlgorithm(String name) { - super(name); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java deleted file mode 100644 index 46684f48ad4a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java +++ /dev/null @@ -1,405 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.keys.cryptography.CryptographyServiceVersion; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.implementation.KeyClientImpl; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; -import com.azure.security.keyvault.keys.implementation.SecretMinClientImpl; -import com.azure.security.keyvault.keys.implementation.models.KeyBundle; -import com.azure.security.keyvault.keys.implementation.models.KeyOperationResult; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.keys.implementation.models.KeyVerifyResult; -import com.azure.security.keyvault.keys.implementation.models.SecretKey; -import com.azure.security.keyvault.keys.implementation.models.SecretRequestAttributes; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import reactor.core.publisher.Mono; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Objects; - -import static com.azure.core.util.FluxUtil.withContext; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.mapKeyEncryptionAlgorithm; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.mapKeySignatureAlgorithm; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.mapWrapAlgorithm; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.transformSecretKey; -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.unpackAndValidateId; -import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.callWithMappedException; -import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyVaultKey; - -public final class CryptographyClientImpl { - private static final ClientLogger LOGGER = new ClientLogger(CryptographyClientImpl.class); - - private final KeyClientImpl keyClient; - private final SecretMinClientImpl secretClient; - - private final String keyId; - - private final String vaultUrl; - private final String keyCollection; - private final String keyName; - private final String keyVersion; - - public CryptographyClientImpl(String keyId, HttpPipeline pipeline, CryptographyServiceVersion serviceVersion) { - Objects.requireNonNull(keyId); - - List data = unpackAndValidateId(keyId, LOGGER); - - this.vaultUrl = data.get(0); - this.keyCollection = data.get(1); - this.keyName = data.get(2); - this.keyVersion = data.get(3); - - this.keyId = keyId; - - this.keyClient = new KeyClientImpl(pipeline, serviceVersion.getVersion()); - this.secretClient = new SecretMinClientImpl(pipeline, serviceVersion.getVersion()); - } - - public String getVaultUrl() { - return vaultUrl; - } - - public String getKeyCollection() { - return keyCollection; - } - - public Mono> getKeyAsync() { - return keyClient.getKeyWithResponseAsync(vaultUrl, keyName, keyVersion) - .doOnRequest(ignored -> LOGGER.verbose("Retrieving key - {}", keyName)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved key - {}", keyName)) - .doOnError(error -> LOGGER.warning("Failed to get key - {}", keyName, error)) - .onErrorMap(KeyVaultErrorException.class, KeyVaultKeysUtils::mapGetKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); - } - - public Response getKey(Context context) { - Response response - = callWithMappedException(() -> keyClient.getKeyWithResponse(vaultUrl, keyName, keyVersion, context), - KeyVaultKeysUtils::mapGetKeyException); - - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); - } - - public Mono getSecretKeyAsync() { - return withContext(context -> secretClient.getSecretWithResponseAsync(vaultUrl, keyName, keyVersion, context)) - .doOnRequest(ignored -> LOGGER.verbose("Retrieving key - {}", keyName)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved key - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to get key - {}", keyName, error)) - .map(response -> transformSecretKey(response.getValue())); - } - - public JsonWebKey getSecretKey() { - return transformSecretKey( - secretClient.getSecretWithResponse(vaultUrl, keyName, keyVersion, Context.NONE).getValue()); - } - - public Mono> setSecretKeyAsync(SecretKey secret, Context context) { - Objects.requireNonNull(secret, "The secret key cannot be null."); - - return secretClient - .setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), secret.getProperties().getTags(), - secret.getProperties().getContentType(), new SecretRequestAttributes(secret.getProperties()), context) - .doOnRequest(ignored -> LOGGER.verbose("Setting secret - {}", secret.getName())) - .doOnSuccess(response -> LOGGER.verbose("Set secret - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to set secret - {}", secret.getName(), error)); - } - - public Response setSecretKey(SecretKey secret, Context context) { - Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); - - return secretClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), - secret.getProperties().getTags(), secret.getProperties().getContentType(), - new SecretRequestAttributes(secret.getProperties()), context); - } - - public Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext cannot be null."); - - return encryptAsync(algorithm, plaintext, null, null, context); - } - - public Mono encryptAsync(EncryptParameters encryptParameters, Context context) { - Objects.requireNonNull(encryptParameters, "Encrypt parameters cannot be null."); - - return encryptAsync(encryptParameters.getAlgorithm(), encryptParameters.getPlainText(), - encryptParameters.getIv(), encryptParameters.getAdditionalAuthenticatedData(), context); - } - - private Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plainText, byte[] iv, - byte[] additionalAuthenticatedData, Context context) { - return keyClient - .encryptAsync(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), plainText, iv, - additionalAuthenticatedData, null, context) - .doOnRequest(ignored -> LOGGER.verbose("Encrypting content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved encrypted content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to encrypt content with algorithm - {}", algorithm, error)) - .map(result -> new EncryptResult(result.getResult(), algorithm, keyId, result.getIv(), - result.getAuthenticationTag(), result.getAdditionalAuthenticatedData())); - } - - public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext cannot be null."); - - return encrypt(algorithm, plaintext, null, null, context); - } - - public EncryptResult encrypt(EncryptParameters encryptParameters, Context context) { - Objects.requireNonNull(encryptParameters, "Encrypt parameters cannot be null."); - - return encrypt(encryptParameters.getAlgorithm(), encryptParameters.getPlainText(), encryptParameters.getIv(), - encryptParameters.getAdditionalAuthenticatedData(), context); - } - - private EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plainText, byte[] iv, - byte[] additionalAuthenticatedData, Context context) { - KeyOperationResult result - = keyClient - .encryptWithResponse(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), plainText, iv, - additionalAuthenticatedData, null, context) - .getValue(); - - return new EncryptResult(result.getResult(), algorithm, keyId, result.getIv(), result.getAuthenticationTag(), - result.getAdditionalAuthenticatedData()); - } - - public Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Ciphertext cannot be null."); - - return decryptAsync(algorithm, ciphertext, null, null, null, context); - } - - public Mono decryptAsync(DecryptParameters decryptParameters, Context context) { - Objects.requireNonNull(decryptParameters, "Decrypt parameters cannot be null."); - - return decryptAsync(decryptParameters.getAlgorithm(), decryptParameters.getCipherText(), - decryptParameters.getIv(), decryptParameters.getAdditionalAuthenticatedData(), - decryptParameters.getAuthenticationTag(), context); - } - - private Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, - byte[] additionalAuthenticatedData, byte[] authenticationTag, Context context) { - return keyClient - .decryptAsync(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), ciphertext, iv, - additionalAuthenticatedData, authenticationTag, context) - .map(result -> new DecryptResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Decrypting content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved decrypted content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to decrypt content with algorithm - {}", algorithm, error)); - } - - public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Ciphertext cannot be null."); - - return decrypt(algorithm, ciphertext, null, null, null, context); - } - - public DecryptResult decrypt(DecryptParameters decryptParameters, Context context) { - Objects.requireNonNull(decryptParameters, "Decrypt parameters cannot be null."); - - return decrypt(decryptParameters.getAlgorithm(), decryptParameters.getCipherText(), decryptParameters.getIv(), - decryptParameters.getAdditionalAuthenticatedData(), decryptParameters.getAuthenticationTag(), context); - } - - private DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, - byte[] additionalAuthenticatedData, byte[] authenticationTag, Context context) { - KeyOperationResult result - = keyClient - .decryptWithResponse(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), ciphertext, - iv, additionalAuthenticatedData, authenticationTag, context) - .getValue(); - - return new DecryptResult(result.getResult(), algorithm, keyId); - } - - public Mono signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - - return keyClient.signAsync(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, context) - .map(result -> new SignResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Signing content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved signed content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to sign content with algorithm - {}", algorithm, error)); - } - - public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - - KeyOperationResult result = keyClient - .signWithResponse(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, context) - .getValue(); - - return new SignResult(result.getResult(), algorithm, keyId); - } - - public Mono verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, - Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - Objects.requireNonNull(signature, "Signature to be verified cannot be null."); - - return keyClient - .verifyAsync(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, signature, context) - .map(result -> new VerifyResult(result.isValue(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Verifying content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved verified content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to verify content with algorithm - {}", algorithm, error)); - } - - public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - Objects.requireNonNull(signature, "Signature to be verified cannot be null."); - - KeyVerifyResult result - = keyClient - .verifyWithResponse(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, - signature, context) - .getValue(); - - return new VerifyResult(result.isValue(), algorithm, keyId); - } - - public Mono wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); - - return keyClient - .wrapKeyAsync(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), key, null, null, null, context) - .map(result -> new WrapResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Wrapping key content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved wrapped key content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to verify content with algorithm - {}", algorithm, error)); - } - - public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); - - KeyOperationResult result - = keyClient - .wrapKeyWithResponse(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), key, null, null, null, - context) - .getValue(); - - return new WrapResult(result.getResult(), algorithm, keyId); - } - - public Mono unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - - return keyClient - .unwrapKeyAsync(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), encryptedKey, null, null, null, - context) - .map(result -> new UnwrapResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Unwrapping key content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved unwrapped key content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to unwrap key content with algorithm - {}", algorithm, error)); - } - - public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - - KeyOperationResult result = keyClient - .unwrapKeyWithResponse(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), encryptedKey, null, null, - null, context) - .getValue(); - - return new UnwrapResult(result.getResult(), algorithm, keyId); - } - - public Mono signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(data, "Data to be signed cannot be null."); - - try { - HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); - MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); - md.update(data); - byte[] digest = md.digest(); - - return signAsync(algorithm, digest, context); - } catch (NoSuchAlgorithmException e) { - return Mono.error(e); - } - } - - public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(data, "Data to be signed cannot be null."); - - try { - HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); - MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); - md.update(data); - byte[] digest = md.digest(); - - return sign(algorithm, digest, context); - } catch (NoSuchAlgorithmException e) { - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } - } - - public Mono verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, - Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(data, "Data to verify cannot be null."); - Objects.requireNonNull(signature, "Signature to be verified cannot be null."); - - try { - HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); - MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); - md.update(data); - byte[] digest = md.digest(); - - return verifyAsync(algorithm, digest, signature, context); - } catch (NoSuchAlgorithmException e) { - return Mono.error(e); - } - } - - public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(data, "Data to verify cannot be null."); - Objects.requireNonNull(signature, "Signature to be verified cannot be null."); - - try { - HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); - MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); - md.update(data); - byte[] digest = md.digest(); - - return verify(algorithm, digest, signature, context); - } catch (NoSuchAlgorithmException e) { - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyUtils.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyUtils.java deleted file mode 100644 index 47e9d69775d1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyUtils.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKeyEncryptionAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKeySignatureAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.SecretKey; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyOperation; -import com.azure.security.keyvault.keys.models.KeyType; -import reactor.core.publisher.Mono; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; -import java.util.Locale; -import java.util.Objects; - -import static com.azure.security.keyvault.keys.models.KeyType.EC; -import static com.azure.security.keyvault.keys.models.KeyType.EC_HSM; -import static com.azure.security.keyvault.keys.models.KeyType.OCT; -import static com.azure.security.keyvault.keys.models.KeyType.OCT_HSM; -import static com.azure.security.keyvault.keys.models.KeyType.RSA; -import static com.azure.security.keyvault.keys.models.KeyType.RSA_HSM; - -/** - * Utility methods for the Cryptography portion of KeyVault Keys. - */ -public final class CryptographyUtils { - private CryptographyUtils() { - // No-op - } - - public static final String SECRETS_COLLECTION = "secrets"; - - public static List unpackAndValidateId(String keyId, ClientLogger logger) { - if (CoreUtils.isNullOrEmpty(keyId)) { - throw logger.logExceptionAsError(new IllegalArgumentException("'keyId' cannot be null or empty.")); - } - - try { - URL url = new URL(keyId); - String[] tokens = url.getPath().split("/"); - String vaultUrl = url.getProtocol() + "://" + url.getHost(); - - if (url.getPort() != -1) { - vaultUrl += ":" + url.getPort(); - } - - String keyCollection = (tokens.length >= 2 ? tokens[1] : null); - String keyName = (tokens.length >= 3 ? tokens[2] : null); - String keyVersion = (tokens.length >= 4 ? tokens[3] : null); - - if (CoreUtils.isNullOrEmpty(vaultUrl)) { - throw logger - .logExceptionAsError(new IllegalArgumentException("Key endpoint in key identifier is invalid.")); - } else if (CoreUtils.isNullOrEmpty(keyName)) { - throw logger - .logExceptionAsError(new IllegalArgumentException("Key name in key identifier is invalid.")); - } - - return Arrays.asList(vaultUrl, keyCollection, keyName, keyVersion); - } catch (MalformedURLException e) { - throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); - } - } - - public static LocalKeyCryptographyClient retrieveJwkAndCreateLocalClient(CryptographyClientImpl implClient) { - // Technically the collection portion of a key identifier should never be null/empty, but we still check for it. - if (!CoreUtils.isNullOrEmpty(implClient.getKeyCollection())) { - // Get the JWK from the service and validate it. Then attempt to create a local cryptography client or - // default to using service-side cryptography. - JsonWebKey jsonWebKey = CryptographyUtils.SECRETS_COLLECTION.equals(implClient.getKeyCollection()) - ? implClient.getSecretKey() - : implClient.getKey(Context.NONE).getValue().getKey(); - - if (jsonWebKey == null) { - throw new IllegalStateException( - "Could not retrieve JSON Web Key to perform local cryptographic operations."); - } else if (!jsonWebKey.isValid()) { - throw new IllegalStateException("The retrieved JSON Web Key is not valid."); - } else { - return createLocalClient(jsonWebKey, implClient); - } - } else { - // Couldn't/didn't create a local cryptography client. - throw new IllegalStateException("Could not create a local cryptography client."); - } - } - - public static Mono - retrieveJwkAndCreateLocalAsyncClient(CryptographyClientImpl implClient) { - // Technically the collection portion of a key identifier should never be null/empty, but we still check for it. - if (!CoreUtils.isNullOrEmpty(implClient.getKeyCollection())) { - // Get the JWK from the service and validate it. Then attempt to create a local cryptography client or - // default to using service-side cryptography. - Mono jsonWebKeyMono = CryptographyUtils.SECRETS_COLLECTION.equals(implClient.getKeyCollection()) - ? implClient.getSecretKeyAsync() - : implClient.getKeyAsync().map(keyVaultKeyResponse -> keyVaultKeyResponse.getValue().getKey()); - - return jsonWebKeyMono.handle((jsonWebKey, sink) -> { - if (!jsonWebKey.isValid()) { - sink.error(new IllegalStateException("The retrieved JSON Web Key is not valid.")); - } else { - sink.next(createLocalClient(jsonWebKey, implClient)); - } - }); - } else { - // Couldn't/didn't create a local cryptography client. - return Mono.error(new IllegalStateException( - "Could not create a local cryptography client. Key collection is null or empty.")); - } - } - - public static LocalKeyCryptographyClient createLocalClient(JsonWebKey jsonWebKey, - CryptographyClientImpl implClient) { - - if (!KeyType.values().contains(jsonWebKey.getKeyType())) { - throw new IllegalArgumentException( - String.format("The JSON Web Key type: %s is not supported.", jsonWebKey.getKeyType().toString())); - } - - if (jsonWebKey.getKeyType().equals(RSA) || jsonWebKey.getKeyType().equals(RSA_HSM)) { - return new RsaKeyCryptographyClient(jsonWebKey, implClient); - } else if (jsonWebKey.getKeyType().equals(EC) || jsonWebKey.getKeyType().equals(EC_HSM)) { - return new EcKeyCryptographyClient(jsonWebKey, implClient); - } else if (jsonWebKey.getKeyType().equals(OCT) || jsonWebKey.getKeyType().equals(OCT_HSM)) { - return new AesKeyCryptographyClient(jsonWebKey, implClient); - } - - // Should never reach this point. - throw new IllegalStateException("Could not create local cryptography client."); - } - - public static void verifyKeyPermissions(JsonWebKey jsonWebKey, KeyOperation keyOperation) { - if (!jsonWebKey.getKeyOps().contains(keyOperation)) { - String keyOperationName = keyOperation == null ? null : keyOperation.toString().toLowerCase(Locale.ROOT); - - throw new UnsupportedOperationException(String.format("The %s operation is not allowed for key with id: %s", - keyOperationName, jsonWebKey.getId())); - } - } - - public static boolean isThrowableRetryable(Throwable e) { - if (e instanceof HttpResponseException) { - int statusCode = ((HttpResponseException) e).getResponse().getStatusCode(); - - // Not a retriable error code. - return statusCode != 501 - && statusCode != 505 - && (statusCode >= 500 || statusCode == 408 || statusCode == 429); - } else { - // Not a service-related transient error. - return false; - } - } - - /* - * Determines whether the key is valid and of required size. - * - * @param key The key to be checked. - * @param keySizeInBytes The minimum size required for the key - */ - static void validate(byte[] key, int keySizeInBytes) { - if (key == null) { - throw new IllegalArgumentException("key must not be null"); - } - - if (key.length < keySizeInBytes) { - throw new IllegalArgumentException(String.format("key must be at least %d bits long", keySizeInBytes << 3)); - } - } - - /* - * Compares two byte arrays in constant time. - * - * @param self - * The first byte array to compare - * @param other - * The second byte array to compare - * @return - * True if the two byte arrays are equal. - */ - static boolean sequenceEqualConstantTime(byte[] self, byte[] other) { - if (self == null) { - throw new IllegalArgumentException("self"); - } - - if (other == null) { - throw new IllegalArgumentException("other"); - } - - // Constant time comparison of two byte arrays - long difference = (self.length & 0xffffffffL) ^ (other.length & 0xffffffffL); - - for (int i = 0; i < self.length && i < other.length; i++) { - difference |= (self[i] ^ other[i]) & 0xffffffffL; - } - - return difference == 0; - } - - static JsonWebKey transformSecretKey(SecretKey secretKey) { - return new JsonWebKey().setId(secretKey.getId()) - .setK(Base64.getUrlDecoder().decode(secretKey.getValue())) - .setKeyType(KeyType.OCT) - .setKeyOps(Arrays.asList(KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY, KeyOperation.ENCRYPT, - KeyOperation.DECRYPT)); - } - - static JsonWebKeyEncryptionAlgorithm mapKeyEncryptionAlgorithm(EncryptionAlgorithm algorithm) { - return JsonWebKeyEncryptionAlgorithm.fromString(Objects.toString(algorithm, null)); - } - - static JsonWebKeySignatureAlgorithm mapKeySignatureAlgorithm(SignatureAlgorithm algorithm) { - return JsonWebKeySignatureAlgorithm.fromString(Objects.toString(algorithm, null)); - } - - static JsonWebKeyEncryptionAlgorithm mapWrapAlgorithm(KeyWrapAlgorithm algorithm) { - return JsonWebKeyEncryptionAlgorithm.fromString(Objects.toString(algorithm, null)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/EcKeyCryptographyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/EcKeyCryptographyClient.java deleted file mode 100644 index c550884960e6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/EcKeyCryptographyClient.java +++ /dev/null @@ -1,335 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.Context; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyOperation; -import reactor.core.publisher.Mono; - -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.Security; -import java.util.Objects; - -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.verifyKeyPermissions; - -class EcKeyCryptographyClient extends LocalKeyCryptographyClient { - private final KeyPair ecKeyPair; - private final Provider provider; - - EcKeyCryptographyClient(JsonWebKey jsonWebKey, CryptographyClientImpl implClient) { - super(jsonWebKey, implClient); - - provider = Security.getProvider("SunEC"); - ecKeyPair = jsonWebKey.toEc(jsonWebKey.hasPrivateKey(), provider); - } - - @Override - public Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - throw new UnsupportedOperationException("The encrypt operation is not supported for EC keys."); - } - - @Override - public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - throw new UnsupportedOperationException("The encrypt operation is not supported for EC keys."); - } - - @Override - public Mono encryptAsync(EncryptParameters options, Context context) { - throw new UnsupportedOperationException("The encrypt operation is not supported for EC keys."); - } - - @Override - public EncryptResult encrypt(EncryptParameters options, Context context) { - throw new UnsupportedOperationException("The encrypt operation is not supported for EC keys."); - } - - @Override - public Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - throw new UnsupportedOperationException("The decrypt operation is not supported for EC keys."); - } - - @Override - public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - throw new UnsupportedOperationException("The decrypt operation is not supported for EC keys."); - } - - @Override - public Mono decryptAsync(DecryptParameters options, Context context) { - throw new UnsupportedOperationException("The decrypt operation is not supported for EC keys."); - } - - @Override - public DecryptResult decrypt(DecryptParameters options, Context context) { - throw new UnsupportedOperationException("The decrypt operation is not supported for EC keys."); - } - - @Override - public Mono signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.signAsync(algorithm, digest, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (ecKeyPair.getPrivate() == null) { - if (implClient != null) { - return implClient.signAsync(algorithm, digest, context); - } - - throw new IllegalArgumentException( - "The private portion of the key is not locally available to perform the sign operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.SIGN); - - Ecdsa algo; - - if (baseAlgorithm instanceof Ecdsa) { - algo = (Ecdsa) baseAlgorithm; - } else { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - ISignatureTransform signer = algo.createSignatureTransform(ecKeyPair, provider); - - return Mono.fromCallable(() -> new SignResult(signer.sign(digest), algorithm, jsonWebKey.getId())); - } - - @Override - public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.sign(algorithm, digest, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (ecKeyPair.getPrivate() == null) { - if (implClient != null) { - return implClient.sign(algorithm, digest, context); - } - - throw new IllegalArgumentException( - "The private portion of the key is not locally available to perform the sign operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.SIGN); - - Ecdsa algo; - - if (baseAlgorithm instanceof Ecdsa) { - algo = (Ecdsa) baseAlgorithm; - } else { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - ISignatureTransform signer = algo.createSignatureTransform(ecKeyPair, provider); - - try { - return new SignResult(signer.sign(digest), algorithm, jsonWebKey.getId()); - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException(e); - } - } - } - - @Override - public Mono verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, - Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - Objects.requireNonNull(signature, "Signature to be verified cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.verifyAsync(algorithm, digest, signature, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (ecKeyPair.getPublic() == null) { - if (implClient != null) { - return implClient.verifyAsync(algorithm, digest, signature, context); - } - - throw new IllegalArgumentException( - "The public portion of the key is not locally available to perform the verify operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.VERIFY); - - Ecdsa algo; - - if (baseAlgorithm instanceof Ecdsa) { - algo = (Ecdsa) baseAlgorithm; - } else { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - ISignatureTransform signer = algo.createSignatureTransform(ecKeyPair, provider); - - return Mono - .fromCallable(() -> new VerifyResult(signer.verify(digest, signature), algorithm, jsonWebKey.getId())); - } - - @Override - public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); - Objects.requireNonNull(digest, "Digest content cannot be null."); - Objects.requireNonNull(signature, "Signature to be verified cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.verify(algorithm, digest, signature, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (ecKeyPair.getPublic() == null) { - if (implClient != null) { - return implClient.verify(algorithm, digest, signature, context); - } - - throw new IllegalArgumentException( - "The public portion of the key is not locally available to perform the verify operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.VERIFY); - - Ecdsa algo; - - if (baseAlgorithm instanceof Ecdsa) { - algo = (Ecdsa) baseAlgorithm; - } else { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - ISignatureTransform signer = algo.createSignatureTransform(ecKeyPair, provider); - - try { - return new VerifyResult(signer.verify(digest, signature), algorithm, jsonWebKey.getId()); - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException(e); - } - } - } - - @Override - public Mono wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context) { - throw new UnsupportedOperationException("The key wrap operation is not supported for EC keys."); - } - - @Override - public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context) { - throw new UnsupportedOperationException("The key wrap operation is not supported for EC keys."); - } - - @Override - public Mono unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - throw new UnsupportedOperationException("The key unwrap operation is not supported for EC keys."); - } - - @Override - public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - throw new UnsupportedOperationException("The key unwrap operation is not supported for EC keys."); - } - - @Override - public Mono signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context) { - try { - return signAsync(algorithm, calculateDigest(algorithm, data), context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { - try { - return sign(algorithm, calculateDigest(algorithm, data), context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, - Context context) { - try { - return verifyAsync(algorithm, calculateDigest(algorithm, data), signature, context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { - try { - return verify(algorithm, calculateDigest(algorithm, data), signature, context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - private static byte[] calculateDigest(SignatureAlgorithm algorithm, byte[] data) throws NoSuchAlgorithmException { - HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); - MessageDigest md = MessageDigest.getInstance(Objects.toString(hashAlgorithm, null)); - - md.update(data); - - return md.digest(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Ecdsa.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Ecdsa.java deleted file mode 100644 index 4f11dae58829..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Ecdsa.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.logging.ClientLogger; - -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.Provider; -import java.security.Signature; - -abstract class Ecdsa extends AsymmetricSignatureAlgorithm { - private static final ClientLogger LOGGER = new ClientLogger(Ecdsa.class); - - protected Ecdsa() { - super("NONEwithECDSA"); - } - - public ISignatureTransform createSignatureTransform(KeyPair key, Provider provider) { - return new EcdsaSignatureTransform(key, provider, this); - } - - public abstract int getDigestLength(); - - public abstract int getCoordLength(); - - class EcdsaSignatureTransform implements ISignatureTransform { - private static final String ALGORITHM = "NONEwithECDSA"; - private final KeyPair keyPair; - private final Provider provider; - private final Ecdsa algorithm; - - EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) { - this.keyPair = keyPair; - this.provider = provider; - this.algorithm = algorithm; - } - - @Override - public byte[] sign(byte[] digest) throws GeneralSecurityException { - checkDigestLength(digest); - Signature signature = Signature.getInstance(ALGORITHM, provider); - signature.initSign(keyPair.getPrivate()); - signature.update(digest); - return SignatureEncoding.fromAsn1Der(signature.sign(), algorithm); - } - - @Override - public boolean verify(byte[] digest, byte[] signature) throws GeneralSecurityException { - Signature verify = Signature.getInstance(ALGORITHM, provider); - checkDigestLength(digest); - signature = SignatureEncoding.toAsn1Der(signature, algorithm); - verify.initVerify(keyPair.getPublic()); - verify.update(digest); - return verify.verify(signature); - } - - private void checkDigestLength(byte[] digest) { - if (digest.length != getDigestLength()) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("Invalid digest length.")); - } - } - - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256.java deleted file mode 100644 index 295d28e3d1b3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256.java +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Es256 extends Ecdsa { - public static final String ALGORITHM_NAME = "ES256"; - - @Override - public int getDigestLength() { - return 32; - } - - @Override - public int getCoordLength() { - return 32; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256k.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256k.java deleted file mode 100644 index d4f271e69781..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es256k.java +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Es256k extends Ecdsa { - public static final String ALGORITHM_NAME = "ES256K"; - - @Override - public int getDigestLength() { - return 32; - } - - @Override - public int getCoordLength() { - return 32; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es384.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es384.java deleted file mode 100644 index bf608e547be8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es384.java +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Es384 extends Ecdsa { - public static final String ALGORITHM_NAME = "ES384"; - - @Override - public int getDigestLength() { - return 48; - } - - @Override - public int getCoordLength() { - return 48; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es512.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es512.java deleted file mode 100644 index 23f083495d13..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Es512.java +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -class Es512 extends Ecdsa { - public static final String ALGORITHM_NAME = "ES512"; - - @Override - public int getDigestLength() { - return 64; - } - - @Override - public int getCoordLength() { - return 66; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/HashAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/HashAlgorithm.java deleted file mode 100644 index 2a4f4f2e2691..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/HashAlgorithm.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -enum HashAlgorithm { - - SHA_256("SHA-256"), SHA_384("SHA-384"), SHA_512("SHA-512"); - - private final String value; - - /** - * Creates a custom value for EncryptionAlgorithm. - * - * @param value the custom value - */ - HashAlgorithm(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/IAuthenticatedCryptoTransform.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/IAuthenticatedCryptoTransform.java deleted file mode 100644 index 05860cd41bdf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/IAuthenticatedCryptoTransform.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -interface IAuthenticatedCryptoTransform extends ICryptoTransform { - - byte[] getTag(); -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ICryptoTransform.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ICryptoTransform.java deleted file mode 100644 index 17a6ea5eb10c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ICryptoTransform.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -/** - * Defines the basic operations of cryptographic transformations. - */ -interface ICryptoTransform { - - /** - * Transforms the specified region of the specified byte array as a single operation. - * - * @param input The byte array to be transformed - * @return The transformed result. - */ - byte[] doFinal(byte[] input) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException; - - /** - * Factory Strategy for ICryptoTransform instances - * - * @param Type of the context object used for a particular factory implementation. - */ - interface Factory { - - /** - * @param context The context required for the creation of a new ICryptoTransform instance - * @return The new instance. - * @throws InvalidKeyException if a particular key is invalid (invalid encoding, wrong length, uninitialized, etc). - * @throws NoSuchAlgorithmException if a particular cryptographic algorithm is requested but is not available in the environment. - * @throws NoSuchPaddingException if a particular padding mechanism is requested but is not available in the environment. - * @throws InvalidAlgorithmParameterException if a particular algorithm parameters is invalid or inappropriate. - */ - ICryptoTransform create(T context) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, - InvalidAlgorithmParameterException; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ISignatureTransform.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ISignatureTransform.java deleted file mode 100644 index eee648926fc5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/ISignatureTransform.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import java.security.GeneralSecurityException; - -interface ISignatureTransform { - - byte[] sign(byte[] digest) throws GeneralSecurityException; - - boolean verify(byte[] digest, byte[] signature) throws GeneralSecurityException; -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalEncryptionAlgorithm.java deleted file mode 100644 index 8ff755bdf0c7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalEncryptionAlgorithm.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -/* - * Abstract base class for all encryption implementation. - * - */ -abstract class LocalEncryptionAlgorithm extends Algorithm { - - protected LocalEncryptionAlgorithm(String name) { - super(name); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyCryptographyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyCryptographyClient.java deleted file mode 100644 index 601d90a54438..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyCryptographyClient.java +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.Context; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import reactor.core.publisher.Mono; - -public abstract class LocalKeyCryptographyClient { - final CryptographyClientImpl implClient; - final JsonWebKey jsonWebKey; - - LocalKeyCryptographyClient(JsonWebKey jsonWebKey, CryptographyClientImpl implClient) { - this.jsonWebKey = jsonWebKey; - this.implClient = implClient; - } - - public abstract Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context); - - public abstract EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context); - - public abstract Mono encryptAsync(EncryptParameters encryptParameters, Context context); - - public abstract EncryptResult encrypt(EncryptParameters encryptParameters, Context context); - - public abstract Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context); - - public abstract DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context); - - public abstract Mono decryptAsync(DecryptParameters decryptParameters, Context context); - - public abstract DecryptResult decrypt(DecryptParameters decryptParameters, Context context); - - public abstract Mono signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context); - - public abstract SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context); - - public abstract Mono verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, - Context context); - - public abstract VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context); - - public abstract Mono wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context); - - public abstract WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context); - - public abstract Mono unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context); - - public abstract UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context); - - public abstract Mono signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context); - - public abstract SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context); - - public abstract Mono verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, - Context context); - - public abstract VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, - Context context); - - public JsonWebKey getJsonWebKey() { - return jsonWebKey; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyWrapAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyWrapAlgorithm.java deleted file mode 100644 index e7e1aef72fbb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalKeyWrapAlgorithm.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -/** - * Abstract base class for all key wrap implementation. - * - */ -abstract class LocalKeyWrapAlgorithm extends Algorithm { - - /* - * Constructor. - * - * @param name The name of the algorithm. - */ - LocalKeyWrapAlgorithm(String name) { - super(name); - } - - /* - * Creates a {@link ICryptoTransform} implementation for encryption. - * Uses the default AES-KW initialization vector. - * @param key - * The AES key material to be used. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createEncryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, - InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for encryption that - * uses the specified provider for the Java Security API. Uses the default AES-KW initialization vector. - * - * @param key - * The AES key material to be used. - * @param provider - * The provider to use. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createEncryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for encryption - * using the supplied initialization vector. - * @param key - * The AES key material to be used. - * @param iv - * The initialization vector to be used. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createEncryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for encryption - * using the supplied initialization vector and the specific provider for the Java Security API. - * @param key - * The AES key material to be used. - * @param iv - * The initialization vector to be used. - * @param provider - * The provider to use. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for decryption. - * Uses the default AES-KW initialization vector. - * @param key - * The AES key material to be used. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createDecryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, - InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for decryption that - * uses the specified provider for the Java Security API. Uses the default AES-KW initialization vector. - * - * @param key - * The AES key material to be used. - * @param provider - * The provider to use. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createDecryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for decryption - * using the supplied initialization vector. - * @param key - * The AES key material to be used. - * @param iv - * The initialization vector to be used. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createDecryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for decryption - * using the supplied initialization vector and the specific provider for the Java Security API. - * @param key - * The AES key material to be used. - * @param iv - * The initialization vector to be used. - * @param provider - * The provider to use. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalSignatureAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalSignatureAlgorithm.java deleted file mode 100644 index bbd8ea0b0ac9..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/LocalSignatureAlgorithm.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -abstract class LocalSignatureAlgorithm extends Algorithm { - - protected LocalSignatureAlgorithm(String name) { - super(name); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Rsa15.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Rsa15.java deleted file mode 100644 index 7cd85d06724c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/Rsa15.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -class Rsa15 extends RsaEncryption { - static class Rsa15Decryptor implements ICryptoTransform { - private final Cipher cipher; - - Rsa15Decryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - // Create a cipher object using the provider, if specified - if (provider == null) { - cipher = Cipher.getInstance(RSA15); - } else { - cipher = Cipher.getInstance(RSA15, provider); - } - - // encrypt the plain text using the public key - cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - } - - static class Rsa15Encryptor implements ICryptoTransform { - - private final Cipher cipher; - - Rsa15Encryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - // Create a cipher object using the provider, if specified - if (provider == null) { - cipher = Cipher.getInstance(RSA15); - } else { - cipher = Cipher.getInstance(RSA15, provider); - } - - // encrypt the plain text using the public key - cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - - } - - static final String RSA15 = "RSA/ECB/PKCS1Padding"; - - public static final String ALGORITHM_NAME = "RSA1_5"; - - Rsa15() { - super(ALGORITHM_NAME); - } - - @Override - public ICryptoTransform createEncryptor(KeyPair keyPair) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return createEncryptor(keyPair, null); - } - - @Override - public ICryptoTransform createEncryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return new Rsa15Encryptor(keyPair, provider); - } - - @Override - public ICryptoTransform createDecryptor(KeyPair keyPair) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return createDecryptor(keyPair, null); - } - - @Override - public ICryptoTransform createDecryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return new Rsa15Decryptor(keyPair, provider); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaEncryption.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaEncryption.java deleted file mode 100644 index 78f1875ee13b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaEncryption.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -abstract class RsaEncryption extends AsymmetricEncryptionAlgorithm { - - protected RsaEncryption(String name) { - super(name); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaKeyCryptographyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaKeyCryptographyClient.java deleted file mode 100644 index 26bc693a4065..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaKeyCryptographyClient.java +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.Context; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyOperation; -import reactor.core.publisher.Mono; - -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Objects; - -import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.verifyKeyPermissions; - -class RsaKeyCryptographyClient extends LocalKeyCryptographyClient { - private final KeyPair rsaKeyPair; - - RsaKeyCryptographyClient(JsonWebKey jsonWebKey, CryptographyClientImpl implClient) { - super(jsonWebKey, implClient); - - rsaKeyPair = jsonWebKey.toRsa(jsonWebKey.hasPrivateKey()); - } - - @Override - public Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.encryptAsync(algorithm, plaintext, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPublic() == null) { - if (implClient != null) { - return implClient.encryptAsync(algorithm, plaintext, context); - } - - throw new IllegalArgumentException( - "The public portion of the key is not available to perform the encrypt operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.ENCRYPT); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - return Mono.fromCallable(() -> { - ICryptoTransform transform = algo.createEncryptor(rsaKeyPair); - - return new EncryptResult(transform.doFinal(plaintext), algorithm, jsonWebKey.getId()); - }); - } - - @Override - public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.encrypt(algorithm, plaintext, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPublic() == null) { - if (implClient != null) { - return implClient.encrypt(algorithm, plaintext, context); - } - - throw new IllegalArgumentException( - "The public portion of the key is not available to perform the encrypt operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.ENCRYPT); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - try { - ICryptoTransform transform = algo.createEncryptor(rsaKeyPair); - - return new EncryptResult(transform.doFinal(plaintext), algorithm, jsonWebKey.getId()); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono encryptAsync(EncryptParameters encryptParameters, Context context) { - return Mono.fromCallable(() -> encrypt(encryptParameters, context)); - } - - @Override - public EncryptResult encrypt(EncryptParameters encryptParameters, Context context) { - Objects.requireNonNull(encryptParameters, "Encrypt parameters cannot be null."); - - return encrypt(encryptParameters.getAlgorithm(), encryptParameters.getPlainText(), context); - } - - @Override - public Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Ciphertext cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.decryptAsync(algorithm, ciphertext, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPrivate() == null) { - if (implClient != null) { - return implClient.decryptAsync(algorithm, ciphertext, context); - } - - throw new IllegalArgumentException( - "The private portion of the key is not available to perform the decrypt operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.DECRYPT); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - return Mono.fromCallable(() -> { - ICryptoTransform transform = algo.createDecryptor(rsaKeyPair); - - return new DecryptResult(transform.doFinal(ciphertext), algorithm, jsonWebKey.getId()); - }); - } - - @Override - public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Ciphertext cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.decrypt(algorithm, ciphertext, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPrivate() == null) { - if (implClient != null) { - return implClient.decrypt(algorithm, ciphertext, context); - } - - throw new IllegalArgumentException( - "The private portion of the key is not available to perform the decrypt operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.DECRYPT); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - try { - ICryptoTransform transform = algo.createDecryptor(rsaKeyPair); - - return new DecryptResult(transform.doFinal(ciphertext), algorithm, jsonWebKey.getId()); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono decryptAsync(DecryptParameters decryptParameters, Context context) { - return Mono.fromCallable(() -> decrypt(decryptParameters, context)); - } - - @Override - public DecryptResult decrypt(DecryptParameters decryptParameters, Context context) { - Objects.requireNonNull(decryptParameters, "Decrypt parameters cannot be null."); - - return decrypt(decryptParameters.getAlgorithm(), decryptParameters.getCipherText(), context); - } - - @Override - public Mono signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context) { - return implClient != null - ? implClient.signAsync(algorithm, digest, context) - : Mono.error( - new UnsupportedOperationException("The sign operation on local RSA key is not currently supported.")); - } - - @Override - public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { - if (implClient != null) { - return implClient.sign(algorithm, digest, context); - } else { - throw new UnsupportedOperationException("The sign operation on local RSA key is not currently supported."); - } - } - - @Override - public Mono verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, - Context context) { - return implClient != null - ? implClient.verifyAsync(algorithm, digest, signature, context) - : Mono.error(new UnsupportedOperationException( - "The verify operation on a local RSA key is not currently supported.")); - } - - @Override - public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - if (implClient != null) { - return implClient.verify(algorithm, digest, signature, context); - } else { - throw new UnsupportedOperationException( - "The verify operation on a local RSA key is not currently supported."); - } - } - - @Override - public Mono wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(keyToWrap, "Key content to be wrapped cannot be null."); - - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.wrapKeyAsync(algorithm, keyToWrap, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPublic() == null) { - if (implClient != null) { - return implClient.wrapKeyAsync(algorithm, keyToWrap, context); - } - - throw new IllegalArgumentException( - "The public portion of the key is not available to perform the key wrap operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.WRAP_KEY); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - return Mono.fromCallable(() -> { - ICryptoTransform transform = algo.createEncryptor(rsaKeyPair); - - return new WrapResult(transform.doFinal(keyToWrap), algorithm, jsonWebKey.getId()); - }); - } - - @Override - public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] keyToWrap, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(keyToWrap, "Key content to be wrapped cannot be null."); - - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.wrapKey(algorithm, keyToWrap, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPublic() == null) { - if (implClient != null) { - return implClient.wrapKey(algorithm, keyToWrap, context); - } - - throw new IllegalArgumentException( - "The public portion of the key is not available to perform the key wrap operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.WRAP_KEY); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - try { - ICryptoTransform transform = algo.createEncryptor(rsaKeyPair); - - return new WrapResult(transform.doFinal(keyToWrap), algorithm, jsonWebKey.getId()); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.unwrapKeyAsync(algorithm, encryptedKey, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPrivate() == null) { - if (implClient != null) { - return implClient.unwrapKeyAsync(algorithm, encryptedKey, context); - } - - throw new IllegalArgumentException( - "The private portion of the key is not available to perform the key unwrap operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.UNWRAP_KEY); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - return Mono.fromCallable(() -> { - ICryptoTransform transform = algo.createDecryptor(rsaKeyPair); - - return new UnwrapResult(transform.doFinal(encryptedKey), algorithm, jsonWebKey.getId()); - }); - } - - @Override - public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { - Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); - Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - - // Interpret the requested algorithm - Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString()); - - if (baseAlgorithm == null) { - if (implClient != null) { - return implClient.unwrapKey(algorithm, encryptedKey, context); - } - - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } else if (!(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { - throw new RuntimeException(new NoSuchAlgorithmException(algorithm.toString())); - } - - if (rsaKeyPair.getPrivate() == null) { - if (implClient != null) { - return implClient.unwrapKey(algorithm, encryptedKey, context); - } - - throw new IllegalArgumentException( - "The private portion of the key is not available to perform the key unwrap operation."); - } - - verifyKeyPermissions(jsonWebKey, KeyOperation.UNWRAP_KEY); - - AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm; - - try { - ICryptoTransform transform = algo.createDecryptor(rsaKeyPair); - - return new UnwrapResult(transform.doFinal(encryptedKey), algorithm, jsonWebKey.getId()); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context) { - try { - return signAsync(algorithm, calculateDigest(algorithm, data), context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { - try { - return sign(algorithm, calculateDigest(algorithm, data), context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public Mono verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, - Context context) { - try { - return verifyAsync(algorithm, calculateDigest(algorithm, data), signature, context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { - try { - return verify(algorithm, calculateDigest(algorithm, data), signature, context); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - private static byte[] calculateDigest(SignatureAlgorithm algorithm, byte[] data) throws NoSuchAlgorithmException { - HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); - MessageDigest md = MessageDigest.getInstance(Objects.toString(hashAlgorithm, null)); - - md.update(data); - - return md.digest(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaOaep.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaOaep.java deleted file mode 100644 index a91f4c54d89f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/RsaOaep.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -class RsaOaep extends RsaEncryption { - static class RsaOaepDecryptor implements ICryptoTransform { - private final Cipher cipher; - - RsaOaepDecryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - // Create a cipher object using the provider, if specified - if (provider == null) { - cipher = Cipher.getInstance(RSAOAEP); - } else { - cipher = Cipher.getInstance(RSAOAEP, provider); - } - - // encrypt the plain text using the public key - cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - - } - - static class RsaOaepEncryptor implements ICryptoTransform { - private final Cipher cipher; - - RsaOaepEncryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - // Create a cipher object using the provider, if specified - if (provider == null) { - cipher = Cipher.getInstance(RSAOAEP); - } else { - cipher = Cipher.getInstance(RSAOAEP, provider); - } - - // encrypt the plain text using the public key - cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); - } - - @Override - public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { - return cipher.doFinal(plaintext); - } - - } - - static final String RSAOAEP = "RSA/ECB/OAEPWithSHA1AndMGF1Padding"; - - public static final String ALGORITHM_NAME = "RSA-OAEP"; - - RsaOaep() { - super(ALGORITHM_NAME); - } - - @Override - public ICryptoTransform createEncryptor(KeyPair keyPair) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return createEncryptor(keyPair, null); - } - - @Override - public ICryptoTransform createEncryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return new RsaOaepEncryptor(keyPair, provider); - } - - @Override - public ICryptoTransform createDecryptor(KeyPair keyPair) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return createDecryptor(keyPair, null); - } - - @Override - public ICryptoTransform createDecryptor(KeyPair keyPair, Provider provider) - throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - - return new RsaOaepDecryptor(keyPair, provider); - } - -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureEncoding.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureEncoding.java deleted file mode 100644 index bb5ed4bbcbf8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureEncoding.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.core.util.CoreUtils; - -final class SignatureEncoding { - // SignatureEncoding is intended to be a static class - private SignatureEncoding() { - } - - /* - * Converts an ASN.1 DER encoded ECDSA signature to a raw signature in the form R|S - * @param asn1DerSignature An ASN.1 DER encoded signature - * @param algorithm The algorithm used to produce the given ASN.1 DER encoded signature - * @return The raw format of the given ASN.1 DER encoded signature in the form R|S - */ - static byte[] fromAsn1Der(byte[] asn1DerSignature, Ecdsa algorithm) { - - try { - return Asn1DerSignatureEncoding.decode(asn1DerSignature, algorithm); - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException(ex.getMessage() + " " + CoreUtils.bytesToHexString(asn1DerSignature), - ex); - } - } - - /* - * Converts a raw ECDSA signature in the form R|S to an ASN.1 DER encoded signature. - * @param signature A raw ECDSA signature in the form R|S. - * @param algorithm The algorithm used to produce the given signature. - * @return The ASN.1 DER encoded signature of the given signature. - */ - static byte[] toAsn1Der(byte[] signature, Ecdsa algorithm) { - try { - return Asn1DerSignatureEncoding.encode(signature, algorithm); - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException(ex.getMessage() + " " + CoreUtils.bytesToHexString(signature), ex); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureHashResolver.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureHashResolver.java deleted file mode 100644 index c430b3b0eed7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SignatureHashResolver.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; - -import java.util.HashMap; -import java.util.Map; - -final class SignatureHashResolver { - - public static final SignatureHashResolver DEFAULT; - - static { - Map defaultAlgorithms = new HashMap<>(); - defaultAlgorithms.put(SignatureAlgorithm.ES256, HashAlgorithm.SHA_256); - defaultAlgorithms.put(SignatureAlgorithm.ES256K, HashAlgorithm.SHA_256); - defaultAlgorithms.put(SignatureAlgorithm.ES384, HashAlgorithm.SHA_384); - defaultAlgorithms.put(SignatureAlgorithm.ES512, HashAlgorithm.SHA_512); - defaultAlgorithms.put(SignatureAlgorithm.RS256, HashAlgorithm.SHA_256); - defaultAlgorithms.put(SignatureAlgorithm.RS384, HashAlgorithm.SHA_384); - defaultAlgorithms.put(SignatureAlgorithm.RS512, HashAlgorithm.SHA_512); - defaultAlgorithms.put(SignatureAlgorithm.PS256, HashAlgorithm.SHA_256); - defaultAlgorithms.put(SignatureAlgorithm.PS512, HashAlgorithm.SHA_512); - defaultAlgorithms.put(SignatureAlgorithm.PS384, HashAlgorithm.SHA_384); - - DEFAULT = new SignatureHashResolver(defaultAlgorithms); - } - - private final Map algorithms; - - private SignatureHashResolver(Map algorithms) { - this.algorithms = algorithms; - } - - /** - * Returns the hash algorithm used for signature algorithm. - * - * @param signatureAlgorithm The signature algorithm. - * @return The hash algorithm or null. - */ - public HashAlgorithm get(SignatureAlgorithm signatureAlgorithm) { - return algorithms.get(signatureAlgorithm); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SymmetricEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SymmetricEncryptionAlgorithm.java deleted file mode 100644 index a5b105fe9ee8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/SymmetricEncryptionAlgorithm.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.implementation; - -import javax.crypto.NoSuchPaddingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -/** - * Abstract base class for all symmetric encryption implementation. - */ -abstract class SymmetricEncryptionAlgorithm extends LocalEncryptionAlgorithm { - /* - * Constructor. - * - * @param name The name of the algorithm. - */ - SymmetricEncryptionAlgorithm(String name) { - super(name); - } - - /* - * Creates a {@link ICryptoTransform} implementation for encryption using the supplied initialization vector and the - * specific provider for the Java Security API. - * - * @param key The key material to be used. - * @param iv The initialization vector to be used. - * @param additionalAuthenticatedData The authentication data to be used with authenticating encryption implementation - * (ignored for non-authenticating implementation). - * @return A {@link ICryptoTransform} implementation. - */ - abstract ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for encryption - * using the supplied initialization vector and the specific provider for the Java Security API. - * - * @param key The key material to be used. - * @param iv The initialization vector to be used. - * @param additionalAuthenticatedData The authentication data to be used with authenticating encryption implementation - * (ignored for non-authenticating implementation). - * @param provider The provider to use. - * @return A {@link ICryptoTransform} implementation. - */ - abstract ICryptoTransform createEncryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for decryption using the supplied initialization vector and the - * specific provider for the Java Security API. - * - * @param key The key material to be used. - * @param iv The initialization vector to be used. - * @param additionalAuthenticatedData The authentication data to be used with authenticating encryption implementation - * (ignored for non-authenticating implementation). - * @param authenticationTag The authentication tag to verify when using authenticating encryption implementation - * (ignored for non-authenticating implementation). - * @return A {@link ICryptoTransform} implementation. - */ - abstract ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, - InvalidAlgorithmParameterException; - - /* - * Creates a {@link ICryptoTransform} implementation for decryption using the supplied initialization vector and the - * specific provider for the Java Security API. - * - * @param key The key material to be used. - * @param iv The initialization vector to be used. - * @param additionalAuthenticatedData The authentication data to be used with authenticating encryption implementation - * (ignored for non-authenticating implementation). - * @param authenticationTag The authentication tag to verify when using authenticating encryption implementation - * (ignored for non-authenticating implementation). - * @param provider The provider to use. - * @return A {@link ICryptoTransform} implementation - */ - abstract ICryptoTransform createDecryptor(byte[] key, byte[] iv, byte[] additionalAuthenticatedData, - byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, - NoSuchPaddingException, InvalidAlgorithmParameterException; -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/package-info.java deleted file mode 100644 index a9930930c58c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing internal classes used by the Azure Security Key Vault Keys Cryptography library. - */ -package com.azure.security.keyvault.keys.cryptography.implementation; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptParameters.java deleted file mode 100644 index 8dbbb691c402..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptParameters.java +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.util.CoreUtils; - -import java.util.Objects; - -/** - * A class containing various configuration parameters that can be applied when performing decryption operations. - */ -public final class DecryptParameters { - /** - * The algorithm to be used for decryption. - */ - private final EncryptionAlgorithm algorithm; - - /** - * The content to be decrypted. - */ - private final byte[] ciphertext; - - /** - * Initialization vector to be used in the decryption operation using a symmetric algorithm. - */ - private final byte[] iv; - - /** - * Get additional data to authenticate when performing decryption with an authenticated algorithm. - */ - private final byte[] additionalAuthenticatedData; - - /** - * The tag to authenticate when performing decryption with an authenticated algorithm. - */ - private final byte[] authenticationTag; - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128CBC}. - * - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * @param iv Initialization vector for the decryption operation. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA128CbcParameters(byte[] ciphertext, byte[] iv) { - return new DecryptParameters(EncryptionAlgorithm.A128CBC, ciphertext, iv, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128CBCPAD}. - * - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * @param iv Initialization vector for the decryption operation. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA128CbcPadParameters(byte[] ciphertext, byte[] iv) { - return new DecryptParameters(EncryptionAlgorithm.A128CBCPAD, ciphertext, iv, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128GCM}. - * - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA128GcmParameters(byte[] ciphertext, byte[] iv, byte[] authenticationTag) { - return createA128GcmParameters(ciphertext, iv, authenticationTag, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128GCM}. - * - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA128GcmParameters(byte[] ciphertext, byte[] iv, byte[] authenticationTag, - byte[] additionalAuthenticatedData) { - return new DecryptParameters(EncryptionAlgorithm.A128GCM, ciphertext, iv, authenticationTag, - additionalAuthenticatedData); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192CBC}. - * - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * @param iv Initialization vector for the decryption operation. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA192CbcParameters(byte[] ciphertext, byte[] iv) { - return new DecryptParameters(EncryptionAlgorithm.A192CBC, ciphertext, iv, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192CBCPAD}. - * - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * @param iv Initialization vector for the decryption operation. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA192CbcPadParameters(byte[] ciphertext, byte[] iv) { - return new DecryptParameters(EncryptionAlgorithm.A192CBCPAD, ciphertext, iv, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192GCM}. - * - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA192GcmParameters(byte[] ciphertext, byte[] iv, byte[] authenticationTag) { - return createA192GcmParameters(ciphertext, iv, authenticationTag, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192GCM}. - * - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA192GcmParameters(byte[] ciphertext, byte[] iv, byte[] authenticationTag, - byte[] additionalAuthenticatedData) { - return new DecryptParameters(EncryptionAlgorithm.A192GCM, ciphertext, iv, authenticationTag, - additionalAuthenticatedData); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256CBC}. - * - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * @param iv Initialization vector for the decryption operation. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA256CbcParameters(byte[] ciphertext, byte[] iv) { - return new DecryptParameters(EncryptionAlgorithm.A256CBC, ciphertext, iv, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256CBCPAD}. - * - * @param ciphertext The content to be decrypted. Microsoft recommends you not use CBC without first ensuring the - * integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * @param iv Initialization vector for the decryption operation. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA256CbcPadParameters(byte[] ciphertext, byte[] iv) { - return new DecryptParameters(EncryptionAlgorithm.A256CBCPAD, ciphertext, iv, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256GCM}. - * - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA256GcmParameters(byte[] ciphertext, byte[] iv, byte[] authenticationTag) { - return createA256GcmParameters(ciphertext, iv, authenticationTag, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256GCM}. - * - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createA256GcmParameters(byte[] ciphertext, byte[] iv, byte[] authenticationTag, - byte[] additionalAuthenticatedData) { - return new DecryptParameters(EncryptionAlgorithm.A256GCM, ciphertext, iv, authenticationTag, - additionalAuthenticatedData); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#RSA1_5}. - * - * @param ciphertext The content to be decrypted. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createRsa15Parameters(byte[] ciphertext) { - return new DecryptParameters(EncryptionAlgorithm.RSA1_5, ciphertext, null, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#RSA_OAEP}. - * - * @param ciphertext The content to be decrypted. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createRsaOaepParameters(byte[] ciphertext) { - return new DecryptParameters(EncryptionAlgorithm.RSA_OAEP, ciphertext, null, null, null); - } - - /** - * Factory method to create an instance of {@link DecryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#RSA_OAEP_256}. - * - * @param ciphertext The content to be decrypted. - * - * @return The {@link DecryptParameters}. - */ - public static DecryptParameters createRsaOaep256Parameters(byte[] ciphertext) { - return new DecryptParameters(EncryptionAlgorithm.RSA_OAEP_256, ciphertext, null, null, null); - } - - /** - * Creates an instance of {@link DecryptParameters} with the given parameters. - * - * @param algorithm The algorithm to be used for decryption. - * @param ciphertext The content to be decrypted. - * @param iv Initialization vector for the decryption operation. - * @param authenticationTag The tag to authenticate when performing decryption. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - */ - DecryptParameters(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, byte[] authenticationTag, - byte[] additionalAuthenticatedData) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(ciphertext, "Cipher text content to be decrypted cannot be null."); - - if (algorithm == EncryptionAlgorithm.A128GCM - || algorithm == EncryptionAlgorithm.A192GCM - || algorithm == EncryptionAlgorithm.A256GCM) { - - Objects.requireNonNull(authenticationTag, "Authentication tag cannot be null for GCM decryption."); - } - - this.algorithm = algorithm; - this.ciphertext = CoreUtils.clone(ciphertext); - this.iv = CoreUtils.clone(iv); - this.additionalAuthenticatedData = CoreUtils.clone(additionalAuthenticatedData); - this.authenticationTag = CoreUtils.clone(authenticationTag); - } - - /** - * The algorithm to be used for decryption. - * - * @return The algorithm to be used for decryption. - */ - public EncryptionAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Get the content to be decrypted. - * - * @return The content to be decrypted. - */ - public byte[] getCipherText() { - return CoreUtils.clone(ciphertext); - } - - /** - * Get the initialization vector to be used in the decryption operation using a symmetric algorithm. - * - * @return The initialization vector. - */ - public byte[] getIv() { - return CoreUtils.clone(iv); - } - - /** - * Get additional data to authenticate when performing decryption with an authenticated algorithm. - * - * @return The additional authenticated data. - */ - public byte[] getAdditionalAuthenticatedData() { - return CoreUtils.clone(additionalAuthenticatedData); - } - - /** - * Get the tag to authenticate when performing decryption with an authenticated algorithm. - * - * @return The authentication tag. - */ - public byte[] getAuthenticationTag() { - return CoreUtils.clone(authenticationTag); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptResult.java deleted file mode 100644 index 7d930248c868..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptResult.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.CoreUtils; - -/** - * Represents the details of decrypt operation result. - */ -@Immutable -public final class DecryptResult { - /** - * The decrypted content. - */ - private final byte[] plaintext; - - /** - * The encryption algorithm used for the encryption operation. - */ - private final EncryptionAlgorithm algorithm; - - /** - * The identifier of the key used for the decryption operation. - */ - private final String keyId; - - /** - * Creates the instance of Decrypt Result holding decrypted content. - * @param plaintext The decrypted content. - * @param algorithm The algorithm used to decrypt the content. - * @param keyId The identifier of the key usd for the decryption operation. - */ - public DecryptResult(byte[] plaintext, EncryptionAlgorithm algorithm, String keyId) { - this.plaintext = CoreUtils.clone(plaintext); - this.algorithm = algorithm; - this.keyId = keyId; - } - - /** - * Get the identifier of the key used for the decryption operation - * @return the key identifier - */ - public String getKeyId() { - return keyId; - } - - /** - * Get the encrypted content. - * @return The decrypted content. - */ - public byte[] getPlainText() { - return CoreUtils.clone(plaintext); - } - - /** - * Get the algorithm used for decryption. - * @return The algorithm used. - */ - public EncryptionAlgorithm getAlgorithm() { - return algorithm; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptParameters.java deleted file mode 100644 index da09ed96720e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptParameters.java +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.util.CoreUtils; - -import java.util.Objects; - -/** - * A class containing various configuration parameters that can be applied when performing encryption operations. - */ -public final class EncryptParameters { - /** - * The algorithm to be used for encryption. - */ - private final EncryptionAlgorithm algorithm; - - /** - * The content to be encrypted. - */ - private final byte[] plaintext; - - /** - * Initialization vector to be used in the encryption operation using a symmetric algorithm. - */ - private final byte[] iv; - - /** - * Get additional data to authenticate when performing encryption with an authenticated algorithm. - */ - private final byte[] additionalAuthenticatedData; - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128CBC}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA128CbcParameters(byte[] plaintext) { - return createA128CbcParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128CBC}. - * - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA128CbcParameters(byte[] plaintext, byte[] iv) { - return new EncryptParameters(EncryptionAlgorithm.A128CBC, plaintext, iv, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128CBCPAD}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA128CbcPadParameters(byte[] plaintext) { - return createA128CbcPadParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128CBCPAD}. - * - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA128CbcPadParameters(byte[] plaintext, byte[] iv) { - return new EncryptParameters(EncryptionAlgorithm.A128CBCPAD, plaintext, iv, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128GCM}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA128GcmParameters(byte[] plaintext) { - return createA128GcmParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A128GCM}. - * - * @param plaintext The content to be encrypted. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA128GcmParameters(byte[] plaintext, byte[] additionalAuthenticatedData) { - return new EncryptParameters(EncryptionAlgorithm.A128GCM, plaintext, null, additionalAuthenticatedData); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192CBC}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA192CbcParameters(byte[] plaintext) { - return createA192CbcParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192CBC}. - * - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA192CbcParameters(byte[] plaintext, byte[] iv) { - return new EncryptParameters(EncryptionAlgorithm.A192CBC, plaintext, iv, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192CBCPAD}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA192CbcPadParameters(byte[] plaintext) { - return createA192CbcPadParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192CBCPAD}. - * - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA192CbcPadParameters(byte[] plaintext, byte[] iv) { - return new EncryptParameters(EncryptionAlgorithm.A192CBCPAD, plaintext, iv, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192GCM}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA192GcmParameters(byte[] plaintext) { - return createA192GcmParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A192GCM}. - * - * @param plaintext The content to be encrypted. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA192GcmParameters(byte[] plaintext, byte[] additionalAuthenticatedData) { - return new EncryptParameters(EncryptionAlgorithm.A192GCM, plaintext, null, additionalAuthenticatedData); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256CBC}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA256CbcParameters(byte[] plaintext) { - return createA256CbcParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256CBC}. - * - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA256CbcParameters(byte[] plaintext, byte[] iv) { - return new EncryptParameters(EncryptionAlgorithm.A256CBC, plaintext, iv, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256CBCPAD}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA256CbcPadParameters(byte[] plaintext) { - return createA256CbcPadParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256CBCPAD}. - * - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA256CbcPadParameters(byte[] plaintext, byte[] iv) { - return new EncryptParameters(EncryptionAlgorithm.A256CBCPAD, plaintext, iv, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256GCM}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA256GcmParameters(byte[] plaintext) { - return createA256GcmParameters(plaintext, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#A256GCM}. - * - * @param plaintext The content to be encrypted. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createA256GcmParameters(byte[] plaintext, byte[] additionalAuthenticatedData) { - return new EncryptParameters(EncryptionAlgorithm.A256GCM, plaintext, null, additionalAuthenticatedData); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#RSA1_5}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createRsa15Parameters(byte[] plaintext) { - return new EncryptParameters(EncryptionAlgorithm.RSA1_5, plaintext, null, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#RSA_OAEP}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createRsaOaepParameters(byte[] plaintext) { - return new EncryptParameters(EncryptionAlgorithm.RSA_OAEP, plaintext, null, null); - } - - /** - * Factory method to create an instance of {@link EncryptParameters} with the given parameters for - * {@link EncryptionAlgorithm#RSA_OAEP_256}. - * - * @param plaintext The content to be encrypted. - * - * @return The {@link EncryptParameters}. - */ - public static EncryptParameters createRsaOaep256Parameters(byte[] plaintext) { - return new EncryptParameters(EncryptionAlgorithm.RSA_OAEP_256, plaintext, null, null); - } - - /** - * Creates an instance of {@link EncryptParameters} with the given parameters. - * - * @param algorithm The algorithm to be used for encryption. - * @param plaintext The content to be encrypted. - * @param iv Optional initialization vector for the encryption operation. If you pass your own IV, make sure you - * use a cryptographically random, non-repeating IV. If {@code null}, a cryptographically random IV will be - * generated by Key Vault for service-side operations. For client-side operations, - * {@link java.security.SecureRandom} will be used instead. - * @param additionalAuthenticatedData Additional data to authenticate when using authenticated crypto algorithms. - */ - EncryptParameters(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] additionalAuthenticatedData) { - Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); - Objects.requireNonNull(plaintext, "Plaintext content to be encrypted cannot be null."); - - this.algorithm = algorithm; - this.plaintext = CoreUtils.clone(plaintext); - this.iv = CoreUtils.clone(iv); - this.additionalAuthenticatedData = CoreUtils.clone(additionalAuthenticatedData); - } - - /** - * The algorithm to be used for encryption. - * - * @return The algorithm to be used for encryption. - */ - public EncryptionAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Get the content to be encrypted. - * - * @return The content to be encrypted. - */ - public byte[] getPlainText() { - return CoreUtils.clone(plaintext); - } - - /** - * Get the initialization vector to be used in the encryption operation using a symmetric algorithm. - * - * @return The initialization vector. - */ - public byte[] getIv() { - return CoreUtils.clone(iv); - } - - /** - * Get additional data to authenticate when performing encryption with an authenticated algorithm. - * - * @return The additional authenticated data. - */ - public byte[] getAdditionalAuthenticatedData() { - return CoreUtils.clone(additionalAuthenticatedData); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptResult.java deleted file mode 100644 index 9a8ec8fe25a8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptResult.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.CoreUtils; - -/** - * Represents the details of encrypt operation result. - */ -@Immutable -public final class EncryptResult { - /** - * The encrypted content. - */ - private final byte[] ciphertext; - - /** - * The algorithm used for the encryption operation. - */ - private final EncryptionAlgorithm algorithm; - - /** - * The identifier of the key used for the encryption operation. - */ - private final String keyId; - - /** - * Initialization vector for symmetric algorithms. - */ - private final byte[] iv; - - /** - * The tag to authenticate when performing decryption with an authenticated algorithm. - */ - private final byte[] authenticationTag; - - /** - * Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - */ - private final byte[] additionalAuthenticatedData; - - /** - * Creates the instance of Encrypt Result holding encryption operation response information. - * @param ciphertext The encrypted content. - * @param algorithm The algorithm used to encrypt the content. - * @param keyId The identifier of the key usd for the encryption operation. - */ - public EncryptResult(byte[] ciphertext, EncryptionAlgorithm algorithm, String keyId) { - this(ciphertext, algorithm, keyId, null, null, null); - } - - /** - * Creates the instance of Encrypt Result holding encryption operation response information. - * @param ciphertext The encrypted content. - * @param algorithm The algorithm used to encrypt the content. - * @param keyId The identifier of the key usd for the encryption operation. - * @param iv Initialization vector for symmetric algorithms. - * @param authenticationTag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param additionalAuthenticatedData Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - */ - public EncryptResult(byte[] ciphertext, EncryptionAlgorithm algorithm, String keyId, byte[] iv, - byte[] authenticationTag, byte[] additionalAuthenticatedData) { - this.ciphertext = CoreUtils.clone(ciphertext); - this.algorithm = algorithm; - this.keyId = keyId; - this.iv = CoreUtils.clone(iv); - this.authenticationTag = CoreUtils.clone(authenticationTag); - this.additionalAuthenticatedData = CoreUtils.clone(additionalAuthenticatedData); - } - - /** - * Get the identifier of the key used to do encryption - * @return the key identifier - */ - public String getKeyId() { - return keyId; - } - - /** - * Get the encrypted content. - * @return The encrypted content. - */ - public byte[] getCipherText() { - return CoreUtils.clone(ciphertext); - } - - /** - * Get the encryption algorithm used for encryption. - * @return The encryption algorithm used. - */ - public EncryptionAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Get the initialization vector used by symmetric algorithms. - * - * @return The initialization vector. - */ - public byte[] getIv() { - return CoreUtils.clone(iv); - } - - /** - * Get the tag to authenticate the encrypted content. - * - * @return The authentication tag. - */ - public byte[] getAuthenticationTag() { - return CoreUtils.clone(authenticationTag); - } - - /** - * Get additional data to authenticate the encrypted content. - * - * @return The additional authenticated data. - */ - public byte[] getAdditionalAuthenticatedData() { - return CoreUtils.clone(additionalAuthenticatedData); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptionAlgorithm.java deleted file mode 100644 index 72f9b2e031f6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptionAlgorithm.java +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.util.ExpandableStringEnum; - -import java.util.Collection; - -/** - * Defines values for EncryptionAlgorithm. - */ -public final class EncryptionAlgorithm extends ExpandableStringEnum { - - /** - * Static value RSA_OAEP for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm RSA_OAEP = fromString("RSA-OAEP"); - - /** - * Static value RSA_OAEP_256 for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm RSA_OAEP_256 = fromString("RSA-OAEP-256"); - - /** - * Static value RSA1_5 for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm RSA1_5 = fromString("RSA1_5"); - - /** - * Static value A128CBC for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A128CBC = fromString("A128CBC"); - - /** - * Static value A192CBC for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A192CBC = fromString("A192CBC"); - - /** - * Static value A256CBC for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A256CBC = fromString("A256CBC"); - - /** - * Static value A128CBCPAD for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A128CBCPAD = fromString("A128CBCPAD"); - - /** - * Static value A192CBCPAD for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A192CBCPAD = fromString("A192CBCPAD"); - - /** - * Static value A256CBCPAD for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A256CBCPAD = fromString("A256CBCPAD"); - - /** - * Static value A128CBC_HS256 for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A128CBC_HS256 = fromString("A128CBC-HS256"); - - /** - * Static value A192CBC_HS384 for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A192CBC_HS384 = fromString("A192CBC-HS384"); - - /** - * Static value A256CBC_HS512 for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A256CBC_HS512 = fromString("A256CBC-HS512"); - - /** - * Static value A128GCM for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A128GCM = fromString("A128GCM"); - - /** - * Static value A192GCM for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A192GCM = fromString("A192GCM"); - - /** - * Static value A256GCM for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A256GCM = fromString("A256GCM"); - - /** - * Static value A128KW for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A128KW = fromString("A128KW"); - - /** - * Static value A192KW for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A192KW = fromString("A192KW"); - - /** - * Static value A256KW for EncryptionAlgorithm. - */ - public static final EncryptionAlgorithm A256KW = fromString("A256KW"); - - /** - * Creates a new instance of {@link EncryptionAlgorithm} without a {@link #toString()} value. - *

- * This constructor shouldn't be called as it will produce a {@link EncryptionAlgorithm} which doesn't - * have a String enum value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public EncryptionAlgorithm() { - } - - /** - * Creates or finds a EncryptionAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding EncryptionAlgorithm. - */ - public static EncryptionAlgorithm fromString(String name) { - return fromString(name, EncryptionAlgorithm.class); - } - - /** - * Gets known EncryptionAlgorithm values. - * - * @return known EncryptionAlgorithm values. - */ - public static Collection values() { - return values(EncryptionAlgorithm.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/KeyWrapAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/KeyWrapAlgorithm.java deleted file mode 100644 index 6088d754017f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/KeyWrapAlgorithm.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.util.ExpandableStringEnum; - -import java.util.Collection; - -/** - * Defines values for KeyWrapAlgorithm. - */ -public final class KeyWrapAlgorithm extends ExpandableStringEnum { - - /** - * Static value RSA-OAEP for KeyWrapAlgorithm. - */ - public static final KeyWrapAlgorithm RSA_OAEP = fromString("RSA-OAEP"); - - /** - * Static value RSA-OAEP-256 for KeyWrapAlgorithm. - */ - public static final KeyWrapAlgorithm RSA_OAEP_256 = fromString("RSA-OAEP-256"); - - /** - * Static value RSA1_5 for KeyWrapAlgorithm. - */ - public static final KeyWrapAlgorithm RSA1_5 = fromString("RSA1_5"); - - /** - * Static value A192KW for KeyWrapAlgorithm. - */ - public static final KeyWrapAlgorithm A192KW = fromString("A192KW"); - - /** - * Static value A128KW for KeyWrapAlgorithm. - */ - public static final KeyWrapAlgorithm A128KW = fromString("A128KW"); - - /** - * Static value Unwrap Key for KeyWrapAlgorithm. - */ - public static final KeyWrapAlgorithm A256KW = fromString("A256KW"); - - /** - * Creates a new instance of {@link KeyWrapAlgorithm} without a {@link #toString()} value. - *

- * This constructor shouldn't be called as it will produce a {@link KeyWrapAlgorithm} which doesn't - * have a String enum value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public KeyWrapAlgorithm() { - } - - /** - * Creates or finds a KeyWrapAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyWrapAlgorithm. - */ - public static KeyWrapAlgorithm fromString(String name) { - return fromString(name, KeyWrapAlgorithm.class); - } - - /** - * Gets known KeyWrapAlgorithm values. - * - * @return known KeyWrapAlgorithm values. - */ - public static Collection values() { - return values(KeyWrapAlgorithm.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignResult.java deleted file mode 100644 index 3fae0e2c51fb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignResult.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.CoreUtils; - -/** - * Represents the details of sign operation result. - */ -@Immutable -public final class SignResult { - /** - * The signature created from the digest. - */ - private final byte[] signature; - - /** - * The algorithm used to create the signature. - */ - private final SignatureAlgorithm algorithm; - - /** - * The identifier of the key used for the verify operation. - */ - private final String keyId; - - /** - * Creates the instance of SignResult holding the sign operation response details. - * @param signature The signature created from the digest. - * @param algorithm The algorithm used to sign the digest. - * @param keyId The identifier of the key usd for the sign operation. - */ - public SignResult(byte[] signature, SignatureAlgorithm algorithm, String keyId) { - this.signature = CoreUtils.clone(signature); - this.algorithm = algorithm; - this.keyId = keyId; - } - - /** - * Get the identifier of the key used for the verify operation - * @return the key identifier - */ - public String getKeyId() { - return keyId; - } - - /** - * Get the signature created from the digest. - * @return The signature. - */ - public byte[] getSignature() { - return CoreUtils.clone(signature); - } - - /** - * Get the signature algorithm used to create the signature. - * @return The signature algorithm. - */ - public SignatureAlgorithm getAlgorithm() { - return algorithm; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignatureAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignatureAlgorithm.java deleted file mode 100644 index c8f3b6c0f0d1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/SignatureAlgorithm.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.util.ExpandableStringEnum; - -import java.util.Collection; - -/** - * Defines values for SignatureAlgorithm. - */ -public final class SignatureAlgorithm extends ExpandableStringEnum { - - /** - * Static value PS256 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm PS256 = fromString("PS256"); - - /** - * Static value PS384 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm PS384 = fromString("PS384"); - - /** - * Static value PS512 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm PS512 = fromString("PS512"); - - /** - * Static value RS256 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm RS256 = fromString("RS256"); - - /** - * Static value RS384 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm RS384 = fromString("RS384"); - - /** - * Static value RS512 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm RS512 = fromString("RS512"); - - /** - * Static value ES256 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm ES256 = fromString("ES256"); - - /** - * Static value ES384 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm ES384 = fromString("ES384"); - - /** - * Static value ES512 for SignatureAlgorithm. - */ - public static final SignatureAlgorithm ES512 = fromString("ES512"); - - /** - * Static value ES256K for SignatureAlgorithm. - */ - public static final SignatureAlgorithm ES256K = fromString("ES256K"); - - /** - * Creates a new instance of {@link SignatureAlgorithm} without a {@link #toString()} value. - *

- * This constructor shouldn't be called as it will produce a {@link SignatureAlgorithm} which doesn't - * have a String enum value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public SignatureAlgorithm() { - } - - /** - * Creates or finds a SignatureAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding SignatureAlgorithm. - */ - public static SignatureAlgorithm fromString(String name) { - return fromString(name, SignatureAlgorithm.class); - } - - /** - * Gets the known SignatureAlgorithm values. - * - * @return known SignatureAlgorithm values. - */ - public static Collection values() { - return values(SignatureAlgorithm.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/UnwrapResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/UnwrapResult.java deleted file mode 100644 index 6bcba798d71b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/UnwrapResult.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.CoreUtils; - -/** - * Represents the details of key unwrap operation result. - */ -@Immutable -public final class UnwrapResult { - /** - * The unwrapped key content. - */ - private final byte[] key; - - /** - * The algorithm used for the key wrap operation. - */ - private final KeyWrapAlgorithm algorithm; - - /** - * The identifier of the key used for the key wrap operation. - */ - private final String keyId; - - /** - * Creates the instance of KeyUnwrap Result holding the unwrapped key content. - * - * @param key The unwrapped key content. - * @param algorithm The algorithm used for the operation - * @param keyId The id of key used for the operation - */ - public UnwrapResult(byte[] key, KeyWrapAlgorithm algorithm, String keyId) { - this.key = CoreUtils.clone(key); - this.algorithm = algorithm; - this.keyId = keyId; - } - - /** - * Get the unwrapped key content. - * - * @return The unwrapped key content. - */ - public byte[] getKey() { - return CoreUtils.clone(key); - } - - /** - * Get the algorithm used for key wrap operation. - * - * @return The encryption algorithm used. - */ - public KeyWrapAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Get the identifier of the key used for the key wrap encryption - * - * @return the key identifier - */ - public String getKeyId() { - return keyId; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/VerifyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/VerifyResult.java deleted file mode 100644 index 5c3cb60154f3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/VerifyResult.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.annotation.Immutable; - -/** - * Represents the details of verify operation result. - */ -@Immutable -public final class VerifyResult { - /** - * THe verify operation result. - */ - private final Boolean isValid; - - /** - * The identifier of the key used for the verify operation. - */ - private final String keyId; - - /** - * The algorithm used to verify the signature. - */ - private final SignatureAlgorithm algorithm; - - /** - * Creates the instance of Verify Result holding the verification response information. - * @param isValid The verification info. - * @param algorithm The algorithm used to verify the signature. - * @param keyId The identifier of the key usd for the verify operation. - */ - public VerifyResult(Boolean isValid, SignatureAlgorithm algorithm, String keyId) { - this.isValid = isValid; - this.keyId = keyId; - this.algorithm = algorithm; - } - - /** - * Get the verify operation result. - * @return The verification result. - */ - public Boolean isValid() { - return isValid; - } - - /** - * Get the signature algorithm used to verify the signature. - * @return The signature algorithm. - */ - public SignatureAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Get the identifier of the key used for the verify operation - * @return the key identifier - */ - public String getKeyId() { - return keyId; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/WrapResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/WrapResult.java deleted file mode 100644 index 67c744caf87a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/WrapResult.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.CoreUtils; - -/** - * Represents the details of wrap operation result. - */ -@Immutable -public final class WrapResult { - /** - * The encrypted key content - */ - private final byte[] encryptedKey; - - /** - * The identifier of the key used for the encryption operation. - */ - private final String keyId; - - /** - * The key wrap algorithm used to wrap the key content. - */ - private final KeyWrapAlgorithm algorithm; - - /** - * Creates the instance of KeyWrapResult holding the key wrap operation response details. - * @param encryptedKey The unwrapped key content. - * @param algorithm The algorithm used to wrap the key content. - * @param keyId The identifier of the key usd for the key wrap operation. - */ - public WrapResult(byte[] encryptedKey, KeyWrapAlgorithm algorithm, String keyId) { - this.encryptedKey = CoreUtils.clone(encryptedKey); - this.keyId = keyId; - this.algorithm = algorithm; - } - - /** - * Get the encrypted key content. - * @return The encrypted key. - */ - public byte[] getEncryptedKey() { - return CoreUtils.clone(encryptedKey); - } - - /** - * Get the key wrap algorithm used to wrap the key content. - * @return The key wrap algorithm. - */ - public KeyWrapAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Get the identifier of the key used to do encryption - * @return the key identifier - */ - public String getKeyId() { - return keyId; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/package-info.java deleted file mode 100644 index 24470a861ffb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing classes used for representing output/results of encryption, decryption, signing, verifying, - * key wrapping and unwrapping operations. - */ -package com.azure.security.keyvault.keys.cryptography.models; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/package-info.java deleted file mode 100644 index 42e9ccb2fdf0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/package-info.java +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - *

Azure Key Vault is a cloud-based service - * provided by Microsoft Azure that allows users to securely store and manage cryptographic keys used for encrypting - * and decrypting data. It is a part of Azure Key Vault, which is a cloud-based service for managing cryptographic keys, - * secrets, and certificates.

- * - *

The service supports various cryptographic algorithms and operations, including symmetric and asymmetric - * encryption, digital signatures, hashing, and random number generation. You can use the service to perform - * operations like encrypting sensitive data before storing it, decrypting data when needed, signing data to ensure - * its integrity, and verifying signatures to validate the authenticity of the data.

- * - *

By utilizing Azure Key Vault Cryptography service, you benefit from the strong security features provided - * by Azure Key Vault, such as hardware security modules (HSMs) for key storage and cryptographic operations, - * access control policies, and audit logging. It helps you protect your sensitive data and comply with industry - * standards and regulatory requirements.

- * - *

The Azure Key Vault Keys Cryptography client library allows developers to interact with the Azure Key Vault service - * from their applications. The library provides a set of APIs that enable developers to securely encrypt, decrypt, - * sign, and verify data using cryptographic keys securely stored in Key Vault.

- * - *

Key Concepts:

- * - *

What is a Cryptography Client?

- *

The cryptography client performs the cryptographic operations locally or calls the Azure Key Vault service - * depending on how much key information is available locally. It supports encrypting, decrypting, signing, - * verifying, key wrapping, key unwrapping, and retrieving the configured key. - * Asynchronous (`CryptographyAsyncClient`) and synchronous (`CryptographyClient`) clients exist in the SDK - * allowing for the selection of a client based on an application's use case.

- * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyClient} 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 Cryptography Client

- * - *

The following code sample demonstrates the creation of a - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyClient}, - * using the {@link com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder} to configure it.

- * - * - *
- * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
- *     .keyIdentifier("<your-key-id>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *

Sample: Construct Asynchronous Cryptography Client

- * - *

The following code sample demonstrates the creation of a - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient}, using the - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder} to configure it.

- * - * - *
- * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
- *     .keyIdentifier("<your-key-id>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *
- * - *

Encrypt Data

- * The {@link com.azure.security.keyvault.keys.cryptography.CryptographyClient} or - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient} can be used to encrypt data. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously encrypt data using the - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyClient#encrypt(com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm, byte[])} API.

- * - * - *
- * byte[] plaintext = new byte[100];
- * new Random(0x1234567L).nextBytes(plaintext);
- *
- * EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext);
- *
- * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
- *     encryptResult.getCipherText().length, encryptResult.getAlgorithm());
- * 
- * - * - *

Note: For the asynchronous sample, refer to - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient}.

- * - *
- * - *
- * - *

Decrypt Data

- * The {@link com.azure.security.keyvault.keys.cryptography.CryptographyClient} or - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient} can be used to decrypt data. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously decrypt data using the - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyClient#decrypt(com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm, byte[])} API.

- * - * - *
- * byte[] ciphertext = new byte[100];
- * new Random(0x1234567L).nextBytes(ciphertext);
- *
- * DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext);
- *
- * System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length);
- * 
- * - * - *

Note: For the asynchronous sample, refer to - * {@link com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient}.

- * - * @see com.azure.security.keyvault.keys.cryptography.CryptographyClient - * @see com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient - * @see com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder - */ -package com.azure.security.keyvault.keys.cryptography; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/DeletedKeyHelper.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/DeletedKeyHelper.java deleted file mode 100644 index 1fef1a9218c3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/DeletedKeyHelper.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.JsonWebKey; - -import java.time.OffsetDateTime; - -public final class DeletedKeyHelper { - private static DeletedKeyAccessor accessor; - - public interface DeletedKeyAccessor { - DeletedKey createDeletedKey(JsonWebKey jsonWebKey); - - void setRecoveryId(DeletedKey deletedKey, String recoveryId); - - void setScheduledPurgeDate(DeletedKey deletedKey, OffsetDateTime scheduledPurgeDate); - - void setDeletedOn(DeletedKey deletedKey, OffsetDateTime deletedOn); - } - - public static DeletedKey createDeletedKey(JsonWebKey jsonWebKey) { - if (accessor == null) { - new DeletedKey(); - } - - assert accessor != null; - return accessor.createDeletedKey(jsonWebKey); - } - - public static void setRecoveryId(DeletedKey deletedKey, String recoveryId) { - accessor.setRecoveryId(deletedKey, recoveryId); - } - - public static void setScheduledPurgeDate(DeletedKey deletedKey, OffsetDateTime scheduledPurgeDate) { - accessor.setScheduledPurgeDate(deletedKey, scheduledPurgeDate); - } - - public static void setDeletedOn(DeletedKey deletedKey, OffsetDateTime deletedOn) { - accessor.setDeletedOn(deletedKey, deletedOn); - } - - public static void setAccessor(DeletedKeyAccessor accessor) { - DeletedKeyHelper.accessor = accessor; - } - - private DeletedKeyHelper() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java deleted file mode 100644 index 2f370bbc639a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java +++ /dev/null @@ -1,4639 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -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.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.keys.implementation.models.BackupKeyResult; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyBundle; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyItem; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyListResult; -import com.azure.security.keyvault.keys.implementation.models.GetRandomBytesRequest; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKey; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKeyEncryptionAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKeySignatureAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.KeyAttributes; -import com.azure.security.keyvault.keys.implementation.models.KeyBundle; -import com.azure.security.keyvault.keys.implementation.models.KeyCreateParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyImportParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyItem; -import com.azure.security.keyvault.keys.implementation.models.KeyListResult; -import com.azure.security.keyvault.keys.implementation.models.KeyOperationResult; -import com.azure.security.keyvault.keys.implementation.models.KeyOperationsParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyReleaseParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyReleasePolicy; -import com.azure.security.keyvault.keys.implementation.models.KeyRestoreParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.implementation.models.KeySignParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyUpdateParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.keys.implementation.models.KeyVerifyParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyVerifyResult; -import com.azure.security.keyvault.keys.implementation.models.RandomBytes; -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.KeyType; -import com.azure.security.keyvault.keys.models.ReleaseKeyResult; -import java.util.List; -import java.util.Map; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the KeyClient type. - */ -public final class KeyClientImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KeyClientService service; - - /** - * Api Version. - */ - private final String apiVersion; - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - public String getApiVersion() { - return this.apiVersion; - } - - /** - * The HTTP pipeline to send requests through. - */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * The serializer to serialize an object into a string. - */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * Initializes an instance of KeyClient client. - * - * @param apiVersion Api Version. - */ - public KeyClientImpl(String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of KeyClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. - */ - public KeyClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of KeyClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. - */ - public KeyClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; - this.service = RestProxy.create(KeyClientService.class, this.httpPipeline, this.getSerializerAdapter()); - } - - /** - * The interface defining all the services for KeyClient to be used by the proxy service to perform REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyClient") - public interface KeyClientService { - @Post("/keys/{key-name}/create") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> createKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyCreateParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/create") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response createKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyCreateParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/rotate") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> rotateKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/rotate") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response rotateKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Put("/keys/{key-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> importKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyImportParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Put("/keys/{key-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response importKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyImportParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Delete("/keys/{key-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/keys/{key-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Patch("/keys/{key-name}/{key-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyUpdateParameters parameters, - @HeaderParam("Accept") String accept, Context context); - - @Patch("/keys/{key-name}/{key-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyUpdateParameters parameters, - @HeaderParam("Accept") String accept, Context context); - - @Get("/keys/{key-name}/{key-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/keys/{key-name}/{key-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/keys/{key-name}/versions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeyVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/keys/{key-name}/versions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeyVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/keys") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeys(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/keys") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeysSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/backup") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> backupKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/backup") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response backupKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/restore") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> restoreKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/restore") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response restoreKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/encrypt") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> encrypt(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/encrypt") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response encryptSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/decrypt") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> decrypt(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/decrypt") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response decryptSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/sign") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> sign(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeySignParameters parameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/{key-version}/sign") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response signSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeySignParameters parameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/{key-version}/verify") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> verify(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyVerifyParameters parameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/{key-version}/verify") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response verifySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyVerifyParameters parameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/keys/{key-name}/{key-version}/wrapkey") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> wrapKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/wrapkey") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response wrapKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/unwrapkey") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> unwrapKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/unwrapkey") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response unwrapKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/release") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> release(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyReleaseParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/keys/{key-name}/{key-version}/release") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response releaseSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyReleaseParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Get("/deletedkeys") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedKeys(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedkeys") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedKeysSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedkeys/{key-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedkeys/{key-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/deletedkeys/{key-name}") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> purgeDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/deletedkeys/{key-name}") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response purgeDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/deletedkeys/{key-name}/recover") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> recoverDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/deletedkeys/{key-name}/recover") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response recoverDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/keys/{key-name}/rotationpolicy") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeyRotationPolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/keys/{key-name}/rotationpolicy") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeyRotationPolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Put("/keys/{key-name}/rotationpolicy") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateKeyRotationPolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRotationPolicy keyRotationPolicy, @HeaderParam("Accept") String accept, - Context context); - - @Put("/keys/{key-name}/rotationpolicy") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateKeyRotationPolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRotationPolicy keyRotationPolicy, @HeaderParam("Accept") String accept, - Context context); - - @Post("/rng") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getRandomBytes(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") GetRandomBytesRequest parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/rng") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getRandomBytesSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") GetRandomBytesRequest parameters, @HeaderParam("Accept") String accept, - Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeyVersionsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeyVersionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeysNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeysNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedKeysNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedKeysNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createKeyWithResponseAsync(String vaultBaseUrl, String keyName, KeyType kty, - Integer keySize, Integer publicExponent, List keyOps, KeyAttributes keyAttributes, - Map tags, KeyCurveName crv, KeyReleasePolicy releasePolicy) { - return FluxUtil.withContext(context -> createKeyWithResponseAsync(vaultBaseUrl, keyName, kty, keySize, - publicExponent, keyOps, keyAttributes, tags, crv, releasePolicy, context)); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createKeyWithResponseAsync(String vaultBaseUrl, String keyName, KeyType kty, - Integer keySize, Integer publicExponent, List keyOps, KeyAttributes keyAttributes, - Map tags, KeyCurveName crv, KeyReleasePolicy releasePolicy, Context context) { - final String accept = "application/json"; - KeyCreateParameters parameters = new KeyCreateParameters(); - parameters.setKty(kty); - parameters.setKeySize(keySize); - parameters.setPublicExponent(publicExponent); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setCrv(crv); - parameters.setReleasePolicy(releasePolicy); - return service.createKey(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createKeyAsync(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy) { - return createKeyWithResponseAsync(vaultBaseUrl, keyName, kty, keySize, publicExponent, keyOps, keyAttributes, - tags, crv, releasePolicy).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createKeyAsync(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy, Context context) { - return createKeyWithResponseAsync(vaultBaseUrl, keyName, kty, keySize, publicExponent, keyOps, keyAttributes, - tags, crv, releasePolicy, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createKeyWithResponse(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy, Context context) { - final String accept = "application/json"; - KeyCreateParameters parameters = new KeyCreateParameters(); - parameters.setKty(kty); - parameters.setKeySize(keySize); - parameters.setPublicExponent(publicExponent); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setCrv(crv); - parameters.setReleasePolicy(releasePolicy); - return service.createKeySync(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle createKey(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy) { - return createKeyWithResponse(vaultBaseUrl, keyName, kty, keySize, publicExponent, keyOps, keyAttributes, tags, - crv, releasePolicy, Context.NONE).getValue(); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> rotateKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> rotateKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> rotateKeyWithResponseAsync(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.rotateKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono rotateKeyAsync(String vaultBaseUrl, String keyName) { - return rotateKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono rotateKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return rotateKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response rotateKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.rotateKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle rotateKey(String vaultBaseUrl, String keyName) { - return rotateKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> importKeyWithResponseAsync(String vaultBaseUrl, String keyName, JsonWebKey key, - Boolean hsm, KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return FluxUtil.withContext(context -> importKeyWithResponseAsync(vaultBaseUrl, keyName, key, hsm, - keyAttributes, tags, releasePolicy, context)); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> importKeyWithResponseAsync(String vaultBaseUrl, String keyName, JsonWebKey key, - Boolean hsm, KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy, - Context context) { - final String accept = "application/json"; - KeyImportParameters parameters = new KeyImportParameters(); - parameters.setHsm(hsm); - parameters.setKey(key); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.importKey(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return importKeyWithResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags, releasePolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy, Context context) { - return importKeyWithResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags, releasePolicy, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response importKeyWithResponse(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy, Context context) { - final String accept = "application/json"; - KeyImportParameters parameters = new KeyImportParameters(); - parameters.setHsm(hsm); - parameters.setKey(key); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.importKeySync(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return importKeyWithResponse(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags, releasePolicy, Context.NONE) - .getValue(); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> deleteKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.deleteKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteKeyAsync(String vaultBaseUrl, String keyName) { - return deleteKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return deleteKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.deleteKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedKeyBundle deleteKey(String vaultBaseUrl, String keyName) { - return deleteKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy) { - return FluxUtil.withContext(context -> updateKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, - keyAttributes, tags, releasePolicy, context)); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy, Context context) { - final String accept = "application/json"; - KeyUpdateParameters parameters = new KeyUpdateParameters(); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.updateKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy) { - return updateKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags, releasePolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy, Context context) { - return updateKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags, releasePolicy, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy, Context context) { - final String accept = "application/json"; - KeyUpdateParameters parameters = new KeyUpdateParameters(); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.updateKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return updateKeyWithResponse(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags, releasePolicy, - Context.NONE).getValue(); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion) { - return FluxUtil.withContext(context -> getKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, context)); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, - Context context) { - final String accept = "application/json"; - return service.getKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { - return getKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, Context context) { - return getKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - Context context) { - final String accept = "application/json"; - return service.getKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) { - return getKeyWithResponse(vaultBaseUrl, keyName, keyVersion, Context.NONE).getValue(); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsSinglePageAsync(String vaultBaseUrl, String keyName, - Integer maxresults) { - final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getKeyVersions(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsSinglePageAsync(String vaultBaseUrl, String keyName, - Integer maxresults, Context context) { - final String accept = "application/json"; - return service.getKeyVersions(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeyVersionsAsync(String vaultBaseUrl, String keyName, Integer maxresults) { - return new PagedFlux<>(() -> getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults), - nextLink -> getKeyVersionsNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeyVersionsAsync(String vaultBaseUrl, String keyName, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults, context), - nextLink -> getKeyVersionsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsSinglePage(String vaultBaseUrl, String keyName, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getKeyVersionsSync(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsSinglePage(String vaultBaseUrl, String keyName, Integer maxresults, - Context context) { - final String accept = "application/json"; - Response res - = service.getKeyVersionsSync(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeyVersions(String vaultBaseUrl, String keyName, Integer maxresults) { - return new PagedIterable<>(() -> getKeyVersionsSinglePage(vaultBaseUrl, keyName, maxresults, Context.NONE), - nextLink -> getKeyVersionsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeyVersions(String vaultBaseUrl, String keyName, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getKeyVersionsSinglePage(vaultBaseUrl, keyName, maxresults, context), - nextLink -> getKeyVersionsNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - return service.getKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeysAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getKeysSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getKeysNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeysAsync(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedFlux<>(() -> getKeysSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getKeysNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysSinglePage(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysSinglePage(String vaultBaseUrl, Integer maxresults, Context context) { - final String accept = "application/json"; - Response res - = service.getKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeys(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getKeysSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getKeysNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeys(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedIterable<>(() -> getKeysSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getKeysNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a 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 key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. 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 key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> backupKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a 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 key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. 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 key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.backupKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a 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 key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. 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 key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupKeyAsync(String vaultBaseUrl, String keyName) { - return backupKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a 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 key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. 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 key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return backupKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a 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 key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. 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 key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response backupKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.backupKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a 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 key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. 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 key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) { - return backupKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The 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 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 RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreKeyWithResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup) { - return FluxUtil.withContext(context -> restoreKeyWithResponseAsync(vaultBaseUrl, keyBundleBackup, context)); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The 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 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 RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreKeyWithResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup, - Context context) { - final String accept = "application/json"; - KeyRestoreParameters parameters = new KeyRestoreParameters(); - parameters.setKeyBundleBackup(keyBundleBackup); - return service.restoreKey(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The 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 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 RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup) { - return restoreKeyWithResponseAsync(vaultBaseUrl, keyBundleBackup) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The 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 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 RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, Context context) { - return restoreKeyWithResponseAsync(vaultBaseUrl, keyBundleBackup, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The 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 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 RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreKeyWithResponse(String vaultBaseUrl, byte[] keyBundleBackup, Context context) { - final String accept = "application/json"; - KeyRestoreParameters parameters = new KeyRestoreParameters(); - parameters.setKeyBundleBackup(keyBundleBackup); - return service.restoreKeySync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The 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 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 RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) { - return restoreKeyWithResponse(vaultBaseUrl, keyBundleBackup, Context.NONE).getValue(); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> encryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> encryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> encryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.encrypt(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return encryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return encryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response encryptWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.encryptSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult encrypt(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return encryptWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> decryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> decryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> decryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.decrypt(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return decryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return decryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response decryptWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.decryptSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult decrypt(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return decryptWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> signWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { - return FluxUtil.withContext( - context -> signWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, context)); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> signWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value, Context context) { - final String accept = "application/json"; - KeySignParameters parameters = new KeySignParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - return service.sign(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono signAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value) { - return signWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono signAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value, Context context) { - return signWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response signWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value, Context context) { - final String accept = "application/json"; - KeySignParameters parameters = new KeySignParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - return service.signSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult sign(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value) { - return signWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, Context.NONE).getValue(); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> verifyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return FluxUtil.withContext(context -> verifyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - digest, signature, context)); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> verifyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - final String accept = "application/json"; - KeyVerifyParameters parameters = new KeyVerifyParameters(); - parameters.setAlgorithm(algorithm); - parameters.setDigest(digest); - parameters.setSignature(signature); - return service.verify(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return verifyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - return verifyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response verifyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - final String accept = "application/json"; - KeyVerifyParameters parameters = new KeyVerifyParameters(); - parameters.setAlgorithm(algorithm); - parameters.setDigest(digest); - parameters.setSignature(signature); - return service.verifySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVerifyResult verify(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return verifyWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature, Context.NONE) - .getValue(); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> wrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> wrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> wrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.wrapKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return wrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return wrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response wrapKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.wrapKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult wrapKey(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return wrapKeyWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> unwrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> unwrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> unwrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.unwrapKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return unwrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return unwrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response unwrapKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.unwrapKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return unwrapKeyWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> releaseWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc) { - return FluxUtil.withContext(context -> releaseWithResponseAsync(vaultBaseUrl, keyName, keyVersion, - targetAttestationToken, nonce, enc, context)); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> releaseWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc, - Context context) { - final String accept = "application/json"; - KeyReleaseParameters parameters = new KeyReleaseParameters(); - parameters.setTargetAttestationToken(targetAttestationToken); - parameters.setNonce(nonce); - parameters.setEnc(enc); - return service.release(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono releaseAsync(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc) { - return releaseWithResponseAsync(vaultBaseUrl, keyName, keyVersion, targetAttestationToken, nonce, enc) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono releaseAsync(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc, Context context) { - return releaseWithResponseAsync(vaultBaseUrl, keyName, keyVersion, targetAttestationToken, nonce, enc, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response releaseWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc, Context context) { - final String accept = "application/json"; - KeyReleaseParameters parameters = new KeyReleaseParameters(); - parameters.setTargetAttestationToken(targetAttestationToken); - parameters.setNonce(nonce); - parameters.setEnc(enc); - return service.releaseSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ReleaseKeyResult release(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc) { - return releaseWithResponse(vaultBaseUrl, keyName, keyVersion, targetAttestationToken, nonce, enc, Context.NONE) - .getValue(); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.getDeletedKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - return service.getDeletedKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedKeysAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getDeletedKeysSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getDeletedKeysNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedKeysAsync(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedFlux<>(() -> getDeletedKeysSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedKeysNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysSinglePage(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getDeletedKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysSinglePage(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - Response res - = service.getDeletedKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedKeys(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getDeletedKeysSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getDeletedKeysNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedKeys(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedIterable<>(() -> getDeletedKeysSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedKeysNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> getDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.getDeletedKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedKeyAsync(String vaultBaseUrl, String keyName) { - return getDeletedKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return getDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDeletedKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.getDeletedKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedKeyBundle getDeletedKey(String vaultBaseUrl, String keyName) { - return getDeletedKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> purgeDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.purgeDeletedKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedKeyAsync(String vaultBaseUrl, String keyName) { - return purgeDeletedKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return purgeDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response purgeDeletedKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.purgeDeletedKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void purgeDeletedKey(String vaultBaseUrl, String keyName) { - purgeDeletedKeyWithResponse(vaultBaseUrl, keyName, Context.NONE); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> recoverDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.recoverDeletedKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedKeyAsync(String vaultBaseUrl, String keyName) { - return recoverDeletedKeyWithResponseAsync(vaultBaseUrl, keyName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return recoverDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response recoverDeletedKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.recoverDeletedKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle recoverDeletedKey(String vaultBaseUrl, String keyName) { - return recoverDeletedKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, - String keyName) { - return FluxUtil.withContext(context -> getKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.getKeyRotationPolicy(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyRotationPolicyAsync(String vaultBaseUrl, String keyName) { - return getKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyRotationPolicyAsync(String vaultBaseUrl, String keyName, Context context) { - return getKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKeyRotationPolicyWithResponse(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.getKeyRotationPolicySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyRotationPolicy getKeyRotationPolicy(String vaultBaseUrl, String keyName) { - return getKeyRotationPolicyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, - String keyName, KeyRotationPolicy keyRotationPolicy) { - return FluxUtil.withContext( - context -> updateKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, keyRotationPolicy, context)); - } - - /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, - String keyName, KeyRotationPolicy keyRotationPolicy, Context context) { - final String accept = "application/json"; - return service.updateKeyRotationPolicy(vaultBaseUrl, keyName, this.getApiVersion(), keyRotationPolicy, accept, - context); - } - - /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyRotationPolicyAsync(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy) { - return updateKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, keyRotationPolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyRotationPolicyAsync(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy, Context context) { - return updateKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, keyRotationPolicy, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateKeyRotationPolicyWithResponse(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy, Context context) { - final String accept = "application/json"; - return service.updateKeyRotationPolicySync(vaultBaseUrl, keyName, this.getApiVersion(), keyRotationPolicy, - accept, context); - } - - /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyRotationPolicy updateKeyRotationPolicy(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy) { - return updateKeyRotationPolicyWithResponse(vaultBaseUrl, keyName, keyRotationPolicy, Context.NONE).getValue(); - } - - /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRandomBytesWithResponseAsync(String vaultBaseUrl, int count) { - return FluxUtil.withContext(context -> getRandomBytesWithResponseAsync(vaultBaseUrl, count, context)); - } - - /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRandomBytesWithResponseAsync(String vaultBaseUrl, int count, - Context context) { - final String accept = "application/json"; - GetRandomBytesRequest parameters = new GetRandomBytesRequest(); - parameters.setCount(count); - return service.getRandomBytes(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRandomBytesAsync(String vaultBaseUrl, int count) { - return getRandomBytesWithResponseAsync(vaultBaseUrl, count).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRandomBytesAsync(String vaultBaseUrl, int count, Context context) { - return getRandomBytesWithResponseAsync(vaultBaseUrl, count, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getRandomBytesWithResponse(String vaultBaseUrl, int count, Context context) { - final String accept = "application/json"; - GetRandomBytesRequest parameters = new GetRandomBytesRequest(); - parameters.setCount(count); - return service.getRandomBytesSync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RandomBytes getRandomBytes(String vaultBaseUrl, int count) { - return getRandomBytesWithResponse(vaultBaseUrl, count, Context.NONE).getValue(); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getKeyVersionsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - return service.getKeyVersionsNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res = service.getKeyVersionsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { - final String accept = "application/json"; - Response res = service.getKeyVersionsNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getKeysNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - return service.getKeysNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res = service.getKeysNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { - final String accept = "application/json"; - Response res = service.getKeysNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getDeletedKeysNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - return service.getDeletedKeysNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getDeletedKeysNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - Response res = service.getDeletedKeysNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyPropertiesHelper.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyPropertiesHelper.java deleted file mode 100644 index c22e58b4617f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyPropertiesHelper.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.security.keyvault.keys.models.KeyProperties; - -import java.time.OffsetDateTime; - -public final class KeyPropertiesHelper { - private static KeyPropertiesAccessor accessor; - - public interface KeyPropertiesAccessor { - void setCreatedOn(KeyProperties keyProperties, OffsetDateTime createdOn); - - void setUpdatedOn(KeyProperties keyProperties, OffsetDateTime updatedOn); - - void setRecoveryLevel(KeyProperties keyProperties, String recoveryLevel); - - void setName(KeyProperties keyProperties, String name); - - void setVersion(KeyProperties keyProperties, String version); - - void setId(KeyProperties keyProperties, String id); - - void setManaged(KeyProperties keyProperties, Boolean managed); - - void setRecoverableDays(KeyProperties keyProperties, Integer recoverableDays); - - void setHsmPlatform(KeyProperties keyProperties, String hsmPlatform); - } - - public static void setCreatedOn(KeyProperties keyProperties, OffsetDateTime createdOn) { - accessor.setCreatedOn(keyProperties, createdOn); - } - - public static void setUpdatedOn(KeyProperties keyProperties, OffsetDateTime updatedOn) { - accessor.setUpdatedOn(keyProperties, updatedOn); - } - - public static void setRecoveryLevel(KeyProperties keyProperties, String recoveryLevel) { - accessor.setRecoveryLevel(keyProperties, recoveryLevel); - } - - public static void setName(KeyProperties keyProperties, String name) { - accessor.setName(keyProperties, name); - } - - public static void setVersion(KeyProperties keyProperties, String version) { - accessor.setVersion(keyProperties, version); - } - - public static void setId(KeyProperties keyProperties, String id) { - accessor.setId(keyProperties, id); - } - - public static void setManaged(KeyProperties keyProperties, Boolean managed) { - accessor.setManaged(keyProperties, managed); - } - - public static void setRecoverableDays(KeyProperties keyProperties, Integer recoverableDays) { - accessor.setRecoverableDays(keyProperties, recoverableDays); - } - - public static void setHsmPlatform(KeyProperties keyProperties, String hsmPlatform) { - accessor.setHsmPlatform(keyProperties, hsmPlatform); - } - - public static void setAccessor(KeyPropertiesAccessor accessor) { - KeyPropertiesHelper.accessor = accessor; - } - - private KeyPropertiesHelper() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationLifetimeActionHelper.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationLifetimeActionHelper.java deleted file mode 100644 index deb83aea1739..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationLifetimeActionHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.security.keyvault.keys.implementation.models.LifetimeActionsTrigger; -import com.azure.security.keyvault.keys.implementation.models.LifetimeActionsType; -import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; - -public final class KeyRotationLifetimeActionHelper { - private static KeyRotationLifetimeActionAccessor accessor; - - public interface KeyRotationLifetimeActionAccessor { - KeyRotationLifetimeAction createLifetimeAction(LifetimeActionsTrigger trigger, LifetimeActionsType actionsType); - - LifetimeActionsTrigger getTrigger(KeyRotationLifetimeAction lifetimeAction); - - LifetimeActionsType getActionType(KeyRotationLifetimeAction lifetimeAction); - } - - public static KeyRotationLifetimeAction createLifetimeAction(LifetimeActionsTrigger trigger, - LifetimeActionsType actionsType) { - if (accessor == null) { - new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY); - } - - assert accessor != null; - return accessor.createLifetimeAction(trigger, actionsType); - } - - public static LifetimeActionsTrigger getTrigger(KeyRotationLifetimeAction lifetimeAction) { - return accessor.getTrigger(lifetimeAction); - } - - public static LifetimeActionsType getActionType(KeyRotationLifetimeAction lifetimeAction) { - return accessor.getActionType(lifetimeAction); - } - - public static void setAccessor(KeyRotationLifetimeActionAccessor accessor) { - KeyRotationLifetimeActionHelper.accessor = accessor; - } - - private KeyRotationLifetimeActionHelper() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationPolicyHelper.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationPolicyHelper.java deleted file mode 100644 index 85cfecd64164..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyRotationPolicyHelper.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; - -public final class KeyRotationPolicyHelper { - private static KeyRotationPolicyAccessor accessor; - - public interface KeyRotationPolicyAccessor { - KeyRotationPolicy createPolicy(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy impl); - - com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy getImpl(KeyRotationPolicy policy); - } - - public static KeyRotationPolicy - createPolicy(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy impl) { - // If the class hasn't been loaded yet the accessor won't be set. Attempt to load the class before using the - // accessor. - if (accessor == null) { - new KeyRotationPolicy(); - } - - assert accessor != null; - return accessor.createPolicy(impl); - } - - public static com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy - getImpl(KeyRotationPolicy policy) { - return accessor.getImpl(policy); - } - - public static void setAccessor(KeyRotationPolicyAccessor accessor) { - KeyRotationPolicyHelper.accessor = accessor; - } - - private KeyRotationPolicyHelper() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java deleted file mode 100644 index 85f31cd33374..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelineNextSyncPolicy; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; -import com.azure.core.util.Base64Util; -import com.azure.core.util.BinaryData; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; -import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; - -/** - * A policy that authenticates requests with the Azure Key Vault service. The content added by this policy is - * leveraged in {@link TokenCredential} to get and set the correct "Authorization" header value. - * - * @see TokenCredential - */ -public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); - private static final String BEARER_TOKEN_PREFIX = "Bearer "; - private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; - private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; - private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; - private final boolean disableChallengeResourceVerification; - - /** - * Creates a {@link KeyVaultCredentialPolicy}. - * - * @param credential The token credential to authenticate the request. - */ - public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChallengeResourceVerification) { - super(credential); - - this.disableChallengeResourceVerification = disableChallengeResourceVerification; - } - - /** - * Extracts attributes off the bearer challenge in the authentication header. - * - * @param authenticateHeader The authentication header containing the challenge. - * @param authChallengePrefix The authentication challenge name. - * - * @return A challenge attributes map. - */ - private static Map extractChallengeAttributes(String authenticateHeader, - String authChallengePrefix) { - if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { - return Collections.emptyMap(); - } - - String[] attributes = authenticateHeader.replace("\"", "").substring(authChallengePrefix.length()).split(","); - Map attributeMap = new HashMap<>(); - - for (String pair : attributes) { - // Using trim is ugly, but we need it here because currently the 'claims' attribute comes after two spaces. - String[] keyValue = pair.trim().split("=", 2); - - attributeMap.put(keyValue[0], keyValue[1]); - } - - return attributeMap; - } - - /** - * Verifies whether a challenge is bearer or not. - * - * @param authenticateHeader The authentication header containing all the challenges. - * @param authChallengePrefix The authentication challenge name. - * - * @return A boolean indicating if the challenge is a bearer challenge or not. - */ - private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { - return (!CoreUtils.isNullOrEmpty(authenticateHeader) - && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); - } - - @Override - public Mono authorizeRequest(HttpPipelineCallContext context) { - return Mono.defer(() -> { - HttpRequest request = context.getHttpRequest(); - - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } - - if (this.challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); - } - - // The body is removed from the initial request because Key Vault supports other authentication schemes - // which also protect the body of the request. As a result, before we know the auth scheme we need to - // avoid sending an unprotected body to Key Vault. We don't currently support this enhanced auth scheme - // in the SDK, but we still don't want to send any unprotected data to vaults which require it. - - // Do not overwrite previous contents if retrying after initial request failed (e.g. timeout). - if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) { - if (request.getBody() != null) { - context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBody()); - context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY, - request.getHeaders().getValue(CONTENT_LENGTH)); - request.setHeader(CONTENT_LENGTH, "0"); - request.setBody((Flux) null); - } - } - - return Mono.empty(); - }); - } - - @SuppressWarnings("unchecked") - @Override - public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { - return Mono.defer(() -> { - HttpRequest request = context.getHttpRequest(); - Optional contentOptional = context.getData(KEY_VAULT_STASHED_CONTENT_KEY); - Optional contentLengthOptional = context.getData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY); - - if (request.getBody() == null && contentOptional.isPresent() && contentLengthOptional.isPresent()) { - request.setBody((Flux) contentOptional.get()); - request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); - } - - String authority = getRequestAuthority(request); - Map challengeAttributes - = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - String scope = challengeAttributes.get("resource"); - - if (scope != null) { - scope = scope + "/.default"; - } else { - scope = challengeAttributes.get("scope"); - } - - if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); - - if (this.challenge == null) { - return Mono.just(false); - } - } else { - if (!disableChallengeResourceVerification) { - if (!isChallengeResourceValid(request, scope)) { - throw LOGGER.logExceptionAsError(new RuntimeException(String - .format("The challenge resource '%s' does not match the requested domain. If you wish to " - + "disable this check for your client, pass 'true' to the SecretClientBuilder" - + ".disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information.", scope))); - } - } - - String authorization = challengeAttributes.get("authorization"); - - if (authorization == null) { - authorization = challengeAttributes.get("authorization_uri"); - } - - final URI authorizationUri; - - try { - authorizationUri = new URI(authorization); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError(new RuntimeException( - String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); - } - - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); - - CHALLENGE_CACHE.put(authority, this.challenge); - } - - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); - }); - } - - @Override - public void authorizeRequestSync(HttpPipelineCallContext context) { - HttpRequest request = context.getHttpRequest(); - - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } - - if (this.challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); - - return; - } - - // The body is removed from the initial request because Key Vault supports other authentication schemes which - // also protect the body of the request. As a result, before we know the auth scheme we need to avoid sending an - // unprotected body to Key Vault. We don't currently support this enhanced auth scheme in the SDK, but we still - // don't want to send any unprotected data to vaults which require it. - - // Do not overwrite previous contents if retrying after initial request failed (e.g. timeout). - if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) { - if (request.getBodyAsBinaryData() != null) { - context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBodyAsBinaryData()); - context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY, request.getHeaders().getValue(CONTENT_LENGTH)); - request.setHeader(CONTENT_LENGTH, "0"); - request.setBody((BinaryData) null); - } - } - } - - @Override - public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, HttpResponse response) { - HttpRequest request = context.getHttpRequest(); - Optional contentOptional = context.getData(KEY_VAULT_STASHED_CONTENT_KEY); - Optional contentLengthOptional = context.getData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY); - - if (request.getBody() == null && contentOptional.isPresent() && contentLengthOptional.isPresent()) { - request.setBody((BinaryData) (contentOptional.get())); - request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); - } - - String authority = getRequestAuthority(request); - Map challengeAttributes - = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - String scope = challengeAttributes.get("resource"); - - if (scope != null) { - scope = scope + "/.default"; - } else { - scope = challengeAttributes.get("scope"); - } - - if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); - - if (this.challenge == null) { - return false; - } - } else { - if (!disableChallengeResourceVerification) { - if (!isChallengeResourceValid(request, scope)) { - throw LOGGER.logExceptionAsError(new RuntimeException(String.format( - "The challenge resource '%s' does not match the requested domain. If you wish to disable " - + "this check for your client, pass 'true' to the SecretClientBuilder" - + ".disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information.", - scope))); - } - } - - String authorization = challengeAttributes.get("authorization"); - - if (authorization == null) { - authorization = challengeAttributes.get("authorization_uri"); - } - - final URI authorizationUri; - - try { - authorizationUri = new URI(authorization); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError(new RuntimeException( - String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); - } - - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); - - CHALLENGE_CACHE.put(authority, this.challenge); - } - - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); - - return true; - } - - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { - return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme.")); - } - - HttpPipelineNextPolicy nextPolicy = next.clone(); - - return authorizeRequest(context).then(Mono.defer(next::process)).flatMap(httpResponse -> { - String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return handleChallenge(context, httpResponse, nextPolicy); - } - - return Mono.just(httpResponse); - }); - } - - @Override - public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { - if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { - throw LOGGER.logExceptionAsError( - new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme.")); - } - - HttpPipelineNextSyncPolicy nextPolicy = next.clone(); - - authorizeRequestSync(context); - - HttpResponse httpResponse = next.processSync(); - String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return handleChallengeSync(context, httpResponse, nextPolicy); - } - - return httpResponse; - } - - private Mono handleChallenge(HttpPipelineCallContext context, HttpResponse httpResponse, - HttpPipelineNextPolicy next) { - return authorizeRequestOnChallenge(context, httpResponse).flatMap(authorized -> { - if (authorized) { - // The body needs to be closed or read to the end to release the connection. - httpResponse.close(); - - HttpPipelineNextPolicy nextPolicy = next.clone(); - - return next.process().flatMap(newResponse -> { - String authHeader = newResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (newResponse.getStatusCode() == 401 - && authHeader != null - && isClaimsPresent(newResponse) - && !isClaimsPresent(httpResponse)) { - - return handleChallenge(context, newResponse, nextPolicy); - } else { - return Mono.just(newResponse); - } - }); - } - - return Mono.just(httpResponse); - }); - } - - private HttpResponse handleChallengeSync(HttpPipelineCallContext context, HttpResponse httpResponse, - HttpPipelineNextSyncPolicy next) { - if (authorizeRequestOnChallengeSync(context, httpResponse)) { - // The body needs to be closed or read to the end to release the connection. - httpResponse.close(); - - HttpPipelineNextSyncPolicy nextPolicy = next.clone(); - HttpResponse newResponse = next.processSync(); - String authHeader = newResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (newResponse.getStatusCode() == 401 - && authHeader != null - && isClaimsPresent(newResponse) - && !isClaimsPresent(httpResponse)) { - - return handleChallengeSync(context, newResponse, nextPolicy); - } - - return newResponse; - } - - return httpResponse; - } - - private boolean isClaimsPresent(HttpResponse httpResponse) { - Map challengeAttributes - = extractChallengeAttributes(httpResponse.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - - String error = challengeAttributes.get("error"); - - if (error != null) { - String base64Claims = challengeAttributes.get("claims"); - - return "insufficient_claims".equalsIgnoreCase(error) && base64Claims != null; - } - - return false; - } - - private static class ChallengeParameters { - private final URI authorizationUri; - private final String tenantId; - private final String[] scopes; - - ChallengeParameters(URI authorizationUri, String[] scopes) { - this.authorizationUri = authorizationUri; - tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; - } - - /** - * Get the {@code authorization} or {@code authorization_uri} parameter from the challenge response. - */ - public URI getAuthorizationUri() { - return authorizationUri; - } - - /** - * Get the {@code resource} or {@code scope} parameter from the challenge response. This should end with - * "/.default". - */ - public String[] getScopes() { - return scopes; - } - - /** - * Get the tenant ID from {@code authorizationUri}. - */ - public String getTenantId() { - return tenantId; - } - } - - public static void clearCache() { - CHALLENGE_CACHE.clear(); - } - - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; - } - - return authority; - } - - private static boolean isChallengeResourceValid(HttpRequest request, String scope) { - final URI scopeUri; - - try { - scopeUri = new URI(scope); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError( - new RuntimeException(String.format("The challenge resource '%s' is not a valid URI.", scope), e)); - } - - // Returns false if the host specified in the scope does not match the requested domain. - return request.getUrl() - .getHost() - .toLowerCase(Locale.ROOT) - .endsWith("." + scopeUri.getHost().toLowerCase(Locale.ROOT)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultErrorCodeStrings.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultErrorCodeStrings.java deleted file mode 100644 index 345878813a07..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultErrorCodeStrings.java +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.implementation; - -public final class KeyVaultErrorCodeStrings { - public static final String CREDENTIALS_REQUIRED = "Azure Key Vault credentials are required."; - public static final String VAULT_END_POINT_REQUIRED = "Azure Key Vault endpoint url is required."; - public static final String PARAMETER_REQUIRED = "%s cannot be null."; -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeyHelper.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeyHelper.java deleted file mode 100644 index f38ea8f3a6b7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeyHelper.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; - -public final class KeyVaultKeyHelper { - private static KeyVaultKeyAccessor accessor; - - public interface KeyVaultKeyAccessor { - KeyVaultKey createKeyVaultKey(JsonWebKey jsonWebKey); - } - - public static KeyVaultKey createKeyVaultKey(JsonWebKey jsonWebKey) { - // If the class hasn't been loaded yet the accessor won't be set. Attempt to load the class before using the - // accessor. - if (accessor == null) { - try { - Class.forName(KeyVaultKey.class.getName(), true, KeyVaultKeyHelper.class.getClassLoader()); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - - return accessor.createKeyVaultKey(jsonWebKey); - } - - public static void setAccessor(KeyVaultKeyAccessor accessor) { - KeyVaultKeyHelper.accessor = accessor; - } - - private KeyVaultKeyHelper() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java deleted file mode 100644 index aef4314a5c59..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -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.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.security.keyvault.keys.KeyServiceVersion; -import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; -import com.azure.security.keyvault.keys.cryptography.CryptographyServiceVersion; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Base64; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Utility class for KeyVault Keys. - */ -public final class KeyVaultKeysUtils { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultKeysUtils.class); - - /** - * Creates a {@link CryptographyClientBuilder} based on the values passed from a Keys service client. - * - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param vaultUrl The URL of the KeyVault. - * @param httpPipeline The HttpPipeline to use for the CryptographyClient. - * @param serviceVersion The KeyServiceVersion of the service. - * @return A new {@link CryptographyClientBuilder} with the values passed from a Keys service client. - * @throws IllegalArgumentException If {@code keyName} is null or empty. - */ - public static CryptographyClientBuilder getCryptographyClientBuilder(String keyName, String keyVersion, - String vaultUrl, HttpPipeline httpPipeline, KeyServiceVersion serviceVersion) { - if (CoreUtils.isNullOrEmpty(keyName)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("'keyName' cannot be null or empty.")); - } - - return new CryptographyClientBuilder().keyIdentifier(generateKeyId(keyName, keyVersion, vaultUrl)) - .pipeline(httpPipeline) - .serviceVersion(CryptographyServiceVersion.valueOf(serviceVersion.name())); - } - - /** - * Generates a KeyVault Key ID from the name and version of the key and the KeyVault URL. - * - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param vaultUrl The URL of the KeyVault. - * @return The KeyVault Key ID. - */ - private static String generateKeyId(String keyName, String keyVersion, String vaultUrl) { - StringBuilder stringBuilder = new StringBuilder(vaultUrl); - - if (!vaultUrl.endsWith("/")) { - stringBuilder.append("/"); - } - - stringBuilder.append("keys/").append(keyName); - - if (!CoreUtils.isNullOrEmpty(keyVersion)) { - stringBuilder.append("/").append(keyVersion); - } - - return stringBuilder.toString(); - } - - /** - * Calls a supplier and maps any {@link KeyVaultErrorException} to an {@link HttpResponseException}. - * - * @param The type of the result of the supplier. - * @param call The supplier to call. - * @param exceptionMapper The function to map a {@link KeyVaultErrorException} to an {@link HttpResponseException}. - * @return The result of the supplier. - */ - public static T callWithMappedException(Supplier call, - Function exceptionMapper) { - try { - return call.get(); - } catch (KeyVaultErrorException ex) { - throw exceptionMapper.apply(ex); - } - } - - /** - * Maps a {@link KeyVaultErrorException} to an {@link HttpResponseException} for get key operations. - * - * @param ex The {@link KeyVaultErrorException} to map. - * @return The {@link HttpResponseException} that maps from the {@link KeyVaultErrorException}. - */ - public static HttpResponseException mapGetKeyException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 403) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } - } - - /** - * Unpacks a Key Vault key ID into a name and version. - * - * @param id The Key Vault key ID to unpack. - * @param nameConsumer The consumer to accept the name. - * @param versionConsumer The consumer to accept the version. - */ - public static void unpackId(String id, Consumer nameConsumer, Consumer versionConsumer) { - if (CoreUtils.isNullOrEmpty(id)) { - return; - } - - try { - URL url = new URL(id); - String[] tokens = url.getPath().split("/"); - - if (tokens.length >= 3) { - nameConsumer.accept(tokens[2]); - } - - if (tokens.length >= 4) { - versionConsumer.accept(tokens[3]); - } - } catch (MalformedURLException e) { - // Should never come here. - LOGGER.error("Received Malformed Secret Id URL from KV Service"); - } - } - - /** - * Converts epoch time to OffsetDateTime. - * - * @param epochReader The JsonReader containing the epoch time. - * @return The OffsetDateTime. - * @throws IOException If an error occurs while reading the epoch time. - */ - public static OffsetDateTime epochToOffsetDateTime(JsonReader epochReader) throws IOException { - Instant instant = Instant.ofEpochMilli(epochReader.getLong() * 1000L); - return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); - } - - /** - * Base64 URL encodes the binary value. - *

- * Returns null if the {@code value} is null, returns an empty string if the {@code value} is empty. - * - * @param value The binary value to base64 URL encode. - * @return The base64 URL encoded value. - */ - public static String base64UrlJsonSerialization(byte[] value) { - if (value == null) { - return null; - } else if (value.length == 0) { - return ""; - } else { - return Base64.getUrlEncoder().withoutPadding().encodeToString(value); - } - } - - /** - * Base64 URL decodes the string value. - * - * @param value The string value to base64 URL decode. - * @return The base64 URL decoded value. - */ - public static byte[] base64UrlJsonDeserialization(String value) { - return value == null ? null : Base64.getUrlDecoder().decode(value); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/SecretMinClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/SecretMinClientImpl.java deleted file mode 100644 index 248e8d902163..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/SecretMinClientImpl.java +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -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.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.keys.implementation.models.SecretKey; -import com.azure.security.keyvault.keys.implementation.models.SecretRequestAttributes; -import com.azure.security.keyvault.keys.implementation.models.SecretRequestParameters; -import reactor.core.publisher.Mono; - -import java.util.Map; - -/** - * Initializes a new instance of a minimal Key Vault Secret client. - */ -public final class SecretMinClientImpl { - /** The proxy service used to perform REST calls. */ - private final SecretMinClientService service; - - /** Api Version. */ - private final String apiVersion; - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - public String getApiVersion() { - return this.apiVersion; - } - - /** The HTTP pipeline to send requests through. */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** The serializer to serialize an object into a string. */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * Initializes an instance of KeyClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. - */ - public SecretMinClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); - this.apiVersion = apiVersion; - this.service = RestProxy.create(SecretMinClientService.class, this.httpPipeline, this.getSerializerAdapter()); - } - - /** - * The interface defining a minimal set of services for SecretMinClient to be used by the proxy service to perform - * REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "SecretMinClient") - public interface SecretMinClientService { - @Get("secrets/{secret-name}/{secret-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(code = { 404 }, value = ResourceNotFoundException.class) - @UnexpectedResponseExceptionType(code = { 403 }, value = ResourceModifiedException.class) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> getSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("secrets/{secret-name}/{secret-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(code = { 404 }, value = ResourceNotFoundException.class) - @UnexpectedResponseExceptionType(code = { 403 }, value = ResourceModifiedException.class) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response getSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Put("secrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(code = { 400 }, value = ResourceModifiedException.class) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> setSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Accept") String accept, - @HeaderParam("Content-Type") String contentType, Context context); - - @Put("secrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(code = { 400 }, value = ResourceModifiedException.class) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response setSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Accept") String accept, - @HeaderParam("Content-Type") String contentType, Context context); - } - - /** - * Get a specified secret from a given key vault. - * - *

The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the - * secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, Context context) { - final String accept = "application/json"; - return service.getSecret(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), accept, context); - } - - /** - * Get a specified secret from a given key vault. - * - *

The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the - * secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSecretWithResponse(String vaultBaseUrl, String secretName, String secretVersion, - Context context) { - final String accept = "application/json"; - return service.getSecretSync(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), accept, context); - } - - /** - * Sets a secret in a specified key vault. - * - *

The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param contentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response setSecretWithResponse(String vaultBaseUrl, String secretName, String value, - Map tags, String contentType, SecretRequestAttributes secretAttributes, Context context) { - final String accept = "application/json"; - SecretRequestParameters parameters = new SecretRequestParameters(); - parameters.setValue(value); - parameters.setTags(tags); - parameters.setContentType(contentType); - parameters.setSecretAttributes(secretAttributes); - return service.setSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), parameters, accept, contentType, - context); - } - - /** - * Sets a secret in a specified key vault. - * - *

The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param contentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setSecretWithResponseAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String contentType, SecretRequestAttributes secretAttributes, Context context) { - final String accept = "application/json"; - SecretRequestParameters parameters = new SecretRequestParameters(); - parameters.setValue(value); - parameters.setTags(tags); - parameters.setContentType(contentType); - parameters.setSecretAttributes(secretAttributes); - return service.setSecret(vaultBaseUrl, secretName, this.getApiVersion(), parameters, accept, contentType, - context); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java deleted file mode 100644 index af80db741816..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The object attributes managed by the KeyVault service. - */ -@Fluent -public class Attributes implements JsonSerializable { - /* - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Not before date in UTC. - */ - private Long notBefore; - - /* - * Expiry date in UTC. - */ - private Long expires; - - /* - * Creation time in UTC. - */ - private Long created; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /** - * Creates an instance of Attributes class. - */ - public Attributes() { - } - - /** - * Get the enabled property: Determines whether the object is enabled. - * - * @return the enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled property: Determines whether the object is enabled. - * - * @param enabled the enabled value to set. - * @return the Attributes object itself. - */ - public Attributes setEnabled(Boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore property: Not before date in UTC. - * - * @return the notBefore value. - */ - public OffsetDateTime getNotBefore() { - if (this.notBefore == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); - } - - /** - * Set the notBefore property: Not before date in UTC. - * - * @param notBefore the notBefore value to set. - * @return the Attributes object itself. - */ - public Attributes setNotBefore(OffsetDateTime notBefore) { - if (notBefore == null) { - this.notBefore = null; - } else { - this.notBefore = notBefore.toEpochSecond(); - } - return this; - } - - /** - * Get the expires property: Expiry date in UTC. - * - * @return the expires value. - */ - public OffsetDateTime getExpires() { - if (this.expires == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); - } - - /** - * Set the expires property: Expiry date in UTC. - * - * @param expires the expires value to set. - * @return the Attributes object itself. - */ - public Attributes setExpires(OffsetDateTime expires) { - if (expires == null) { - this.expires = null; - } else { - this.expires = expires.toEpochSecond(); - } - return this; - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * Set the created property: Creation time in UTC. - * - * @param created the created value to set. - * @return the Attributes object itself. - */ - Attributes setCreated(OffsetDateTime created) { - if (created == null) { - this.created = null; - } else { - this.created = created.toEpochSecond(); - } - return this; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Set the updated property: Last updated time in UTC. - * - * @param updated the updated value to set. - * @return the Attributes object itself. - */ - Attributes setUpdated(OffsetDateTime updated) { - if (updated == null) { - this.updated = null; - } else { - this.updated = updated.toEpochSecond(); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", this.enabled); - jsonWriter.writeNumberField("nbf", this.notBefore); - jsonWriter.writeNumberField("exp", this.expires); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Attributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Attributes if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. - * @throws IOException If an error occurs while reading the Attributes. - */ - public static Attributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Attributes deserializedAttributes = new Attributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedAttributes.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - deserializedAttributes.notBefore = reader.getNullable(JsonReader::getLong); - } else if ("exp".equals(fieldName)) { - deserializedAttributes.expires = reader.getNullable(JsonReader::getLong); - } else if ("created".equals(fieldName)) { - deserializedAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedAttributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java deleted file mode 100644 index c6cfc35a17c0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.Base64Url; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The backup key result, containing the backup blob. - */ -@Immutable -public final class BackupKeyResult implements JsonSerializable { - /* - * The backup blob containing the backed up key. - */ - private Base64Url value; - - /** - * Creates an instance of BackupKeyResult class. - */ - public BackupKeyResult() { - } - - /** - * Get the value property: The backup blob containing the backed up key. - * - * @return the value value. - */ - public byte[] getValue() { - if (this.value == null) { - return null; - } - return this.value.decodedBytes(); - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of BackupKeyResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of BackupKeyResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the BackupKeyResult. - */ - public static BackupKeyResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - BackupKeyResult deserializedBackupKeyResult = new BackupKeyResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedBackupKeyResult.value - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedBackupKeyResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java deleted file mode 100644 index 9b4365d2c9b2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Map; - -/** - * A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info. - */ -@Fluent -public final class DeletedKeyBundle extends KeyBundle { - /* - * The url of the recovery object, used to identify and recover the deleted key. - */ - private String recoveryId; - - /* - * The time when the key is scheduled to be purged, in UTC - */ - private Long scheduledPurgeDate; - - /* - * The time when the key was deleted, in UTC - */ - private Long deletedDate; - - /* - * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be - * true. - */ - private Boolean managed; - - /** - * Creates an instance of DeletedKeyBundle class. - */ - public DeletedKeyBundle() { - } - - /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @return the recoveryId value. - */ - public String getRecoveryId() { - return this.recoveryId; - } - - /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedKeyBundle object itself. - */ - public DeletedKeyBundle setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; - } - - /** - * Get the scheduledPurgeDate property: The time when the key is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. - */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); - } - - /** - * Get the deletedDate property: The time when the key was deleted, in UTC. - * - * @return the deletedDate value. - */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); - } - - /** - * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - @Override - public Boolean isManaged() { - return this.managed; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyBundle setKey(JsonWebKey key) { - super.setKey(key); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyBundle setAttributes(KeyAttributes attributes) { - super.setAttributes(attributes); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyBundle setTags(Map tags) { - super.setTags(tags); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyBundle setReleasePolicy(KeyReleasePolicy releasePolicy) { - super.setReleasePolicy(releasePolicy); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("key", getKey()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("release_policy", getReleasePolicy()); - jsonWriter.writeStringField("recoveryId", this.recoveryId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedKeyBundle from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedKeyBundle if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the DeletedKeyBundle. - */ - public static DeletedKeyBundle fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedKeyBundle deserializedDeletedKeyBundle = new DeletedKeyBundle(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("key".equals(fieldName)) { - deserializedDeletedKeyBundle.setKey(JsonWebKey.fromJson(reader)); - } else if ("attributes".equals(fieldName)) { - deserializedDeletedKeyBundle.setAttributes(KeyAttributes.fromJson(reader)); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedKeyBundle.setTags(tags); - } else if ("managed".equals(fieldName)) { - deserializedDeletedKeyBundle.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("release_policy".equals(fieldName)) { - deserializedDeletedKeyBundle.setReleasePolicy(KeyReleasePolicy.fromJson(reader)); - } else if ("recoveryId".equals(fieldName)) { - deserializedDeletedKeyBundle.recoveryId = reader.getString(); - } else if ("scheduledPurgeDate".equals(fieldName)) { - deserializedDeletedKeyBundle.scheduledPurgeDate = reader.getNullable(JsonReader::getLong); - } else if ("deletedDate".equals(fieldName)) { - deserializedDeletedKeyBundle.deletedDate = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedKeyBundle; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java deleted file mode 100644 index 6a11612360d6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Map; - -/** - * The deleted key item containing the deleted key metadata and information about deletion. - */ -@Fluent -public final class DeletedKeyItem extends KeyItem { - /* - * The url of the recovery object, used to identify and recover the deleted key. - */ - private String recoveryId; - - /* - * The time when the key is scheduled to be purged, in UTC - */ - private Long scheduledPurgeDate; - - /* - * The time when the key was deleted, in UTC - */ - private Long deletedDate; - - /* - * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be - * true. - */ - private Boolean managed; - - /** - * Creates an instance of DeletedKeyItem class. - */ - public DeletedKeyItem() { - } - - /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @return the recoveryId value. - */ - public String getRecoveryId() { - return this.recoveryId; - } - - /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedKeyItem object itself. - */ - public DeletedKeyItem setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; - } - - /** - * Get the scheduledPurgeDate property: The time when the key is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. - */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); - } - - /** - * Get the deletedDate property: The time when the key was deleted, in UTC. - * - * @return the deletedDate value. - */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); - } - - /** - * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - @Override - public Boolean isManaged() { - return this.managed; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyItem setKid(String kid) { - super.setKid(kid); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyItem setAttributes(KeyAttributes attributes) { - super.setAttributes(attributes); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedKeyItem setTags(Map tags) { - super.setTags(tags); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kid", getKid()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("recoveryId", this.recoveryId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedKeyItem from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedKeyItem if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the DeletedKeyItem. - */ - public static DeletedKeyItem fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedKeyItem deserializedDeletedKeyItem = new DeletedKeyItem(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kid".equals(fieldName)) { - deserializedDeletedKeyItem.setKid(reader.getString()); - } else if ("attributes".equals(fieldName)) { - deserializedDeletedKeyItem.setAttributes(KeyAttributes.fromJson(reader)); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedKeyItem.setTags(tags); - } else if ("managed".equals(fieldName)) { - deserializedDeletedKeyItem.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("recoveryId".equals(fieldName)) { - deserializedDeletedKeyItem.recoveryId = reader.getString(); - } else if ("scheduledPurgeDate".equals(fieldName)) { - deserializedDeletedKeyItem.scheduledPurgeDate = reader.getNullable(JsonReader::getLong); - } else if ("deletedDate".equals(fieldName)) { - deserializedDeletedKeyItem.deletedDate = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedKeyItem; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java deleted file mode 100644 index ea1014033faf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * A list of keys that have been deleted in this vault. - */ -@Immutable -public final class DeletedKeyListResult implements JsonSerializable { - /* - * A response message containing a list of deleted keys in the vault along with a link to the next page of deleted - * keys - */ - private List value; - - /* - * The URL to get the next set of deleted keys. - */ - private String nextLink; - - /** - * Creates an instance of DeletedKeyListResult class. - */ - public DeletedKeyListResult() { - } - - /** - * Get the value property: A response message containing a list of deleted keys in the vault along with a link to - * the next page of deleted keys. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of deleted keys. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedKeyListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedKeyListResult if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IOException If an error occurs while reading the DeletedKeyListResult. - */ - public static DeletedKeyListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedKeyListResult deserializedDeletedKeyListResult = new DeletedKeyListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> DeletedKeyItem.fromJson(reader1)); - deserializedDeletedKeyListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedDeletedKeyListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedKeyListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java deleted file mode 100644 index 73ccff158f27..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains 'Purgeable' - * the key can be permanently deleted by a privileged user; otherwise, only the system can purge the key, at the end of - * the retention interval. - */ -public final class DeletionRecoveryLevel extends ExpandableStringEnum { - /** - * Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This - * level corresponds to no protection being available against a Delete operation; the data is irretrievably lost - * upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.). - */ - public static final DeletionRecoveryLevel PURGEABLE = fromString("Purgeable"); - - /** - * Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion - * (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval (90 - * days), unless a Purge operation is requested, or the subscription is cancelled. System wil permanently delete it - * after 90 days, if not recovered. - */ - public static final DeletionRecoveryLevel RECOVERABLE_PURGEABLE = fromString("Recoverable+Purgeable"); - - /** - * Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent - * deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention - * interval(90 days) and while the subscription is still available. System wil permanently delete it after 90 days, - * if not recovered. - */ - public static final DeletionRecoveryLevel RECOVERABLE = fromString("Recoverable"); - - /** - * Denotes a vault and subscription state in which deletion is recoverable within retention interval (90 days), - * immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot be - * permanently canceled. System wil permanently delete it after 90 days, if not recovered. - */ - public static final DeletionRecoveryLevel RECOVERABLE_PROTECTED_SUBSCRIPTION - = fromString("Recoverable+ProtectedSubscription"); - - /** - * Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion - * (i.e. purge when 7<= SoftDeleteRetentionInDays < 90). This level guarantees the recoverability of the - * deleted entity during the retention interval, unless a Purge operation is requested, or the subscription is - * cancelled. - */ - public static final DeletionRecoveryLevel CUSTOMIZED_RECOVERABLE_PURGEABLE - = fromString("CustomizedRecoverable+Purgeable"); - - /** - * Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent - * deletion (i.e. purge when 7<= SoftDeleteRetentionInDays < 90).This level guarantees the recoverability of - * the deleted entity during the retention interval and while the subscription is still available. - */ - public static final DeletionRecoveryLevel CUSTOMIZED_RECOVERABLE = fromString("CustomizedRecoverable"); - - /** - * Denotes a vault and subscription state in which deletion is recoverable, immediate and permanent deletion (i.e. - * purge) is not permitted, and in which the subscription itself cannot be permanently canceled when 7<= - * SoftDeleteRetentionInDays < 90. This level guarantees the recoverability of the deleted entity during the - * retention interval, and also reflects the fact that the subscription itself cannot be cancelled. - */ - public static final DeletionRecoveryLevel CUSTOMIZED_RECOVERABLE_PROTECTED_SUBSCRIPTION - = fromString("CustomizedRecoverable+ProtectedSubscription"); - - /** - * Creates a new instance of DeletionRecoveryLevel value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public DeletionRecoveryLevel() { - } - - /** - * Creates or finds a DeletionRecoveryLevel from its string representation. - * - * @param name a name to look for. - * @return the corresponding DeletionRecoveryLevel. - */ - public static DeletionRecoveryLevel fromString(String name) { - return fromString(name, DeletionRecoveryLevel.class); - } - - /** - * Gets known DeletionRecoveryLevel values. - * - * @return known DeletionRecoveryLevel values. - */ - public static Collection values() { - return values(DeletionRecoveryLevel.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java deleted file mode 100644 index 95a6daf023c6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key vault server error. - */ -@Immutable -public final class Error implements JsonSerializable { - /* - * The error code. - */ - private String code; - - /* - * The error message. - */ - private String message; - - /* - * The key vault server error. - */ - private Error innerError; - - /** - * Creates an instance of Error class. - */ - public Error() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the innerError property: The key vault server error. - * - * @return the innerError value. - */ - public Error getInnerError() { - return this.innerError; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Error from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Error if the JsonReader was pointing to an instance of it, or null if it was pointing to - * JSON null. - * @throws IOException If an error occurs while reading the Error. - */ - public static Error fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Error deserializedError = new Error(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedError.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedError.message = reader.getString(); - } else if ("innererror".equals(fieldName)) { - deserializedError.innerError = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java deleted file mode 100644 index 34079cb1b7b7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The get random bytes request object. - */ -@Fluent -public final class GetRandomBytesRequest implements JsonSerializable { - /* - * The requested number of random bytes. - */ - private int count; - - /** - * Creates an instance of GetRandomBytesRequest class. - */ - public GetRandomBytesRequest() { - } - - /** - * Get the count property: The requested number of random bytes. - * - * @return the count value. - */ - public int getCount() { - return this.count; - } - - /** - * Set the count property: The requested number of random bytes. - * - * @param count the count value to set. - * @return the GetRandomBytesRequest object itself. - */ - public GetRandomBytesRequest setCount(int count) { - this.count = count; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("count", this.count); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GetRandomBytesRequest from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GetRandomBytesRequest if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the GetRandomBytesRequest. - */ - public static GetRandomBytesRequest fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GetRandomBytesRequest deserializedGetRandomBytesRequest = new GetRandomBytesRequest(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("count".equals(fieldName)) { - deserializedGetRandomBytesRequest.count = reader.getInt(); - } else { - reader.skipChildren(); - } - } - - return deserializedGetRandomBytesRequest; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java deleted file mode 100644 index 3e8ab290f2d7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java +++ /dev/null @@ -1,613 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyOperation; -import com.azure.security.keyvault.keys.models.KeyType; -import java.io.IOException; -import java.util.List; -import java.util.Objects; - -/** - * As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18. - */ -@Fluent -public final class JsonWebKey implements JsonSerializable { - /* - * Key identifier. - */ - private String kid; - - /* - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ - private KeyType kty; - - /* - * The key_ops property. - */ - private List keyOps; - - /* - * RSA modulus. - */ - private Base64Url n; - - /* - * RSA public exponent. - */ - private Base64Url e; - - /* - * RSA private exponent, or the D component of an EC private key. - */ - private Base64Url d; - - /* - * RSA private key parameter. - */ - private Base64Url dp; - - /* - * RSA private key parameter. - */ - private Base64Url dq; - - /* - * RSA private key parameter. - */ - private Base64Url qi; - - /* - * RSA secret prime. - */ - private Base64Url p; - - /* - * RSA secret prime, with p < q. - */ - private Base64Url q; - - /* - * Symmetric key. - */ - private Base64Url k; - - /* - * Protected Key, used with 'Bring Your Own Key'. - */ - private Base64Url t; - - /* - * Elliptic curve name. - */ - private KeyCurveName crv; - - /* - * X component of an EC public key. - */ - private Base64Url x; - - /* - * Y component of an EC public key. - */ - private Base64Url y; - - /** - * Creates an instance of JsonWebKey class. - */ - public JsonWebKey() { - } - - /** - * Get the kid property: Key identifier. - * - * @return the kid value. - */ - public String getKid() { - return this.kid; - } - - /** - * Set the kid property: Key identifier. - * - * @param kid the kid value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setKid(String kid) { - this.kid = kid; - return this; - } - - /** - * Get the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @return the kty value. - */ - public KeyType getKty() { - return this.kty; - } - - /** - * Set the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @param kty the kty value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setKty(KeyType kty) { - this.kty = kty; - return this; - } - - /** - * Get the keyOps property: The key_ops property. - * - * @return the keyOps value. - */ - public List getKeyOps() { - return this.keyOps; - } - - /** - * Set the keyOps property: The key_ops property. - * - * @param keyOps the keyOps value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setKeyOps(List keyOps) { - this.keyOps = keyOps; - return this; - } - - /** - * Get the n property: RSA modulus. - * - * @return the n value. - */ - public byte[] getN() { - if (this.n == null) { - return null; - } - return this.n.decodedBytes(); - } - - /** - * Set the n property: RSA modulus. - * - * @param n the n value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setN(byte[] n) { - if (n == null) { - this.n = null; - } else { - this.n = Base64Url.encode(CoreUtils.clone(n)); - } - return this; - } - - /** - * Get the e property: RSA public exponent. - * - * @return the e value. - */ - public byte[] getE() { - if (this.e == null) { - return null; - } - return this.e.decodedBytes(); - } - - /** - * Set the e property: RSA public exponent. - * - * @param e the e value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setE(byte[] e) { - if (e == null) { - this.e = null; - } else { - this.e = Base64Url.encode(CoreUtils.clone(e)); - } - return this; - } - - /** - * Get the d property: RSA private exponent, or the D component of an EC private key. - * - * @return the d value. - */ - public byte[] getD() { - if (this.d == null) { - return null; - } - return this.d.decodedBytes(); - } - - /** - * Set the d property: RSA private exponent, or the D component of an EC private key. - * - * @param d the d value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setD(byte[] d) { - if (d == null) { - this.d = null; - } else { - this.d = Base64Url.encode(CoreUtils.clone(d)); - } - return this; - } - - /** - * Get the dp property: RSA private key parameter. - * - * @return the dp value. - */ - public byte[] getDp() { - if (this.dp == null) { - return null; - } - return this.dp.decodedBytes(); - } - - /** - * Set the dp property: RSA private key parameter. - * - * @param dp the dp value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setDp(byte[] dp) { - if (dp == null) { - this.dp = null; - } else { - this.dp = Base64Url.encode(CoreUtils.clone(dp)); - } - return this; - } - - /** - * Get the dq property: RSA private key parameter. - * - * @return the dq value. - */ - public byte[] getDq() { - if (this.dq == null) { - return null; - } - return this.dq.decodedBytes(); - } - - /** - * Set the dq property: RSA private key parameter. - * - * @param dq the dq value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setDq(byte[] dq) { - if (dq == null) { - this.dq = null; - } else { - this.dq = Base64Url.encode(CoreUtils.clone(dq)); - } - return this; - } - - /** - * Get the qi property: RSA private key parameter. - * - * @return the qi value. - */ - public byte[] getQi() { - if (this.qi == null) { - return null; - } - return this.qi.decodedBytes(); - } - - /** - * Set the qi property: RSA private key parameter. - * - * @param qi the qi value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setQi(byte[] qi) { - if (qi == null) { - this.qi = null; - } else { - this.qi = Base64Url.encode(CoreUtils.clone(qi)); - } - return this; - } - - /** - * Get the p property: RSA secret prime. - * - * @return the p value. - */ - public byte[] getP() { - if (this.p == null) { - return null; - } - return this.p.decodedBytes(); - } - - /** - * Set the p property: RSA secret prime. - * - * @param p the p value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setP(byte[] p) { - if (p == null) { - this.p = null; - } else { - this.p = Base64Url.encode(CoreUtils.clone(p)); - } - return this; - } - - /** - * Get the q property: RSA secret prime, with p < q. - * - * @return the q value. - */ - public byte[] getQ() { - if (this.q == null) { - return null; - } - return this.q.decodedBytes(); - } - - /** - * Set the q property: RSA secret prime, with p < q. - * - * @param q the q value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setQ(byte[] q) { - if (q == null) { - this.q = null; - } else { - this.q = Base64Url.encode(CoreUtils.clone(q)); - } - return this; - } - - /** - * Get the k property: Symmetric key. - * - * @return the k value. - */ - public byte[] getK() { - if (this.k == null) { - return null; - } - return this.k.decodedBytes(); - } - - /** - * Set the k property: Symmetric key. - * - * @param k the k value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setK(byte[] k) { - if (k == null) { - this.k = null; - } else { - this.k = Base64Url.encode(CoreUtils.clone(k)); - } - return this; - } - - /** - * Get the t property: Protected Key, used with 'Bring Your Own Key'. - * - * @return the t value. - */ - public byte[] getT() { - if (this.t == null) { - return null; - } - return this.t.decodedBytes(); - } - - /** - * Set the t property: Protected Key, used with 'Bring Your Own Key'. - * - * @param t the t value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setT(byte[] t) { - if (t == null) { - this.t = null; - } else { - this.t = Base64Url.encode(CoreUtils.clone(t)); - } - return this; - } - - /** - * Get the crv property: Elliptic curve name. - * - * @return the crv value. - */ - public KeyCurveName getCrv() { - return this.crv; - } - - /** - * Set the crv property: Elliptic curve name. - * - * @param crv the crv value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setCrv(KeyCurveName crv) { - this.crv = crv; - return this; - } - - /** - * Get the x property: X component of an EC public key. - * - * @return the x value. - */ - public byte[] getX() { - if (this.x == null) { - return null; - } - return this.x.decodedBytes(); - } - - /** - * Set the x property: X component of an EC public key. - * - * @param x the x value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setX(byte[] x) { - if (x == null) { - this.x = null; - } else { - this.x = Base64Url.encode(CoreUtils.clone(x)); - } - return this; - } - - /** - * Get the y property: Y component of an EC public key. - * - * @return the y value. - */ - public byte[] getY() { - if (this.y == null) { - return null; - } - return this.y.decodedBytes(); - } - - /** - * Set the y property: Y component of an EC public key. - * - * @param y the y value to set. - * @return the JsonWebKey object itself. - */ - public JsonWebKey setY(byte[] y) { - if (y == null) { - this.y = null; - } else { - this.y = Base64Url.encode(CoreUtils.clone(y)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kid", this.kid); - jsonWriter.writeStringField("kty", this.kty == null ? null : this.kty.toString()); - jsonWriter.writeArrayField("key_ops", this.keyOps, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeStringField("n", Objects.toString(this.n, null)); - jsonWriter.writeStringField("e", Objects.toString(this.e, null)); - jsonWriter.writeStringField("d", Objects.toString(this.d, null)); - jsonWriter.writeStringField("dp", Objects.toString(this.dp, null)); - jsonWriter.writeStringField("dq", Objects.toString(this.dq, null)); - jsonWriter.writeStringField("qi", Objects.toString(this.qi, null)); - jsonWriter.writeStringField("p", Objects.toString(this.p, null)); - jsonWriter.writeStringField("q", Objects.toString(this.q, null)); - jsonWriter.writeStringField("k", Objects.toString(this.k, null)); - jsonWriter.writeStringField("key_hsm", Objects.toString(this.t, null)); - jsonWriter.writeStringField("crv", this.crv == null ? null : this.crv.toString()); - jsonWriter.writeStringField("x", Objects.toString(this.x, null)); - jsonWriter.writeStringField("y", Objects.toString(this.y, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of JsonWebKey from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of JsonWebKey if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. - * @throws IOException If an error occurs while reading the JsonWebKey. - */ - public static JsonWebKey fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - JsonWebKey deserializedJsonWebKey = new JsonWebKey(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kid".equals(fieldName)) { - deserializedJsonWebKey.kid = reader.getString(); - } else if ("kty".equals(fieldName)) { - deserializedJsonWebKey.kty = KeyType.fromString(reader.getString()); - } else if ("key_ops".equals(fieldName)) { - List keyOps - = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); - deserializedJsonWebKey.keyOps = keyOps; - } else if ("n".equals(fieldName)) { - deserializedJsonWebKey.n - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("e".equals(fieldName)) { - deserializedJsonWebKey.e - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("d".equals(fieldName)) { - deserializedJsonWebKey.d - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("dp".equals(fieldName)) { - deserializedJsonWebKey.dp - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("dq".equals(fieldName)) { - deserializedJsonWebKey.dq - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("qi".equals(fieldName)) { - deserializedJsonWebKey.qi - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("p".equals(fieldName)) { - deserializedJsonWebKey.p - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("q".equals(fieldName)) { - deserializedJsonWebKey.q - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("k".equals(fieldName)) { - deserializedJsonWebKey.k - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("key_hsm".equals(fieldName)) { - deserializedJsonWebKey.t - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("crv".equals(fieldName)) { - deserializedJsonWebKey.crv = KeyCurveName.fromString(reader.getString()); - } else if ("x".equals(fieldName)) { - deserializedJsonWebKey.x - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("y".equals(fieldName)) { - deserializedJsonWebKey.y - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedJsonWebKey; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java deleted file mode 100644 index 3def90a799f4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * algorithm identifier. - */ -public final class JsonWebKeyEncryptionAlgorithm extends ExpandableStringEnum { - /** - * Static value RSA-OAEP for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm RSAOAEP = fromString("RSA-OAEP"); - - /** - * Static value RSA-OAEP-256 for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm RSAOAEP256 = fromString("RSA-OAEP-256"); - - /** - * Static value RSA1_5 for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm RSA15 = fromString("RSA1_5"); - - /** - * Static value A128GCM for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A128GCM = fromString("A128GCM"); - - /** - * Static value A192GCM for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A192GCM = fromString("A192GCM"); - - /** - * Static value A256GCM for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A256GCM = fromString("A256GCM"); - - /** - * Static value A128KW for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A128KW = fromString("A128KW"); - - /** - * Static value A192KW for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A192KW = fromString("A192KW"); - - /** - * Static value A256KW for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A256KW = fromString("A256KW"); - - /** - * Static value A128CBC for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A128CBC = fromString("A128CBC"); - - /** - * Static value A192CBC for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A192CBC = fromString("A192CBC"); - - /** - * Static value A256CBC for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A256CBC = fromString("A256CBC"); - - /** - * Static value A128CBCPAD for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A128CBCPAD = fromString("A128CBCPAD"); - - /** - * Static value A192CBCPAD for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A192CBCPAD = fromString("A192CBCPAD"); - - /** - * Static value A256CBCPAD for JsonWebKeyEncryptionAlgorithm. - */ - public static final JsonWebKeyEncryptionAlgorithm A256CBCPAD = fromString("A256CBCPAD"); - - /** - * Creates a new instance of JsonWebKeyEncryptionAlgorithm value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public JsonWebKeyEncryptionAlgorithm() { - } - - /** - * Creates or finds a JsonWebKeyEncryptionAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding JsonWebKeyEncryptionAlgorithm. - */ - public static JsonWebKeyEncryptionAlgorithm fromString(String name) { - return fromString(name, JsonWebKeyEncryptionAlgorithm.class); - } - - /** - * Gets known JsonWebKeyEncryptionAlgorithm values. - * - * @return known JsonWebKeyEncryptionAlgorithm values. - */ - public static Collection values() { - return values(JsonWebKeyEncryptionAlgorithm.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java deleted file mode 100644 index 791ca48500c0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The signing/verification algorithm identifier. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - */ -public final class JsonWebKeySignatureAlgorithm extends ExpandableStringEnum { - /** - * RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm PS256 = fromString("PS256"); - - /** - * RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm PS384 = fromString("PS384"); - - /** - * RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm PS512 = fromString("PS512"); - - /** - * RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm RS256 = fromString("RS256"); - - /** - * RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm RS384 = fromString("RS384"); - - /** - * RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm RS512 = fromString("RS512"); - - /** - * Reserved. - */ - public static final JsonWebKeySignatureAlgorithm RSNULL = fromString("RSNULL"); - - /** - * ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm ES256 = fromString("ES256"); - - /** - * ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm ES384 = fromString("ES384"); - - /** - * ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm ES512 = fromString("ES512"); - - /** - * ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518. - */ - public static final JsonWebKeySignatureAlgorithm ES256K = fromString("ES256K"); - - /** - * Creates a new instance of JsonWebKeySignatureAlgorithm value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public JsonWebKeySignatureAlgorithm() { - } - - /** - * Creates or finds a JsonWebKeySignatureAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding JsonWebKeySignatureAlgorithm. - */ - public static JsonWebKeySignatureAlgorithm fromString(String name) { - return fromString(name, JsonWebKeySignatureAlgorithm.class); - } - - /** - * Gets known JsonWebKeySignatureAlgorithm values. - * - * @return known JsonWebKeySignatureAlgorithm values. - */ - public static Collection values() { - return values(JsonWebKeySignatureAlgorithm.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java deleted file mode 100644 index 8e207d0f06ee..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The attributes of a key managed by the key vault service. - */ -@Fluent -public final class KeyAttributes extends Attributes { - /* - * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. - */ - private Integer recoverableDays; - - /* - * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains - * 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the system can purge the - * key, at the end of the retention interval. - */ - private DeletionRecoveryLevel recoveryLevel; - - /* - * Indicates if the private key can be exported. Release policy must be provided when creating the first version of - * an exportable key. - */ - private Boolean exportable; - - /* - * The underlying HSM Platform. - */ - private String hsmPlatform; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /* - * Creation time in UTC. - */ - private Long created; - - /** - * Creates an instance of KeyAttributes class. - */ - public KeyAttributes() { - } - - /** - * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when - * softDelete enabled, otherwise 0. - * - * @return the recoverableDays value. - */ - public Integer getRecoverableDays() { - return this.recoverableDays; - } - - /** - * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for keys in the current - * vault. If it contains 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the - * system can purge the key, at the end of the retention interval. - * - * @return the recoveryLevel value. - */ - public DeletionRecoveryLevel getRecoveryLevel() { - return this.recoveryLevel; - } - - /** - * Get the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @return the exportable value. - */ - public Boolean isExportable() { - return this.exportable; - } - - /** - * Set the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @param exportable the exportable value to set. - * @return the KeyAttributes object itself. - */ - public KeyAttributes setExportable(Boolean exportable) { - this.exportable = exportable; - return this; - } - - /** - * Get the hsmPlatform property: The underlying HSM Platform. - * - * @return the hsmPlatform value. - */ - public String getHsmPlatform() { - return this.hsmPlatform; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - @Override - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - @Override - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyAttributes setEnabled(Boolean enabled) { - super.setEnabled(enabled); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public KeyAttributes setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public KeyAttributes setExpires(OffsetDateTime expires) { - super.setExpires(expires); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", isEnabled()); - if (getNotBefore() != null) { - jsonWriter.writeNumberField("nbf", getNotBefore().toEpochSecond()); - } - if (getExpires() != null) { - jsonWriter.writeNumberField("exp", getExpires().toEpochSecond()); - } - jsonWriter.writeBooleanField("exportable", this.exportable); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyAttributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyAttributes if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyAttributes. - */ - public static KeyAttributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyAttributes deserializedKeyAttributes = new KeyAttributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedKeyAttributes.setEnabled(reader.getNullable(JsonReader::getBoolean)); - } else if ("nbf".equals(fieldName)) { - Long notBeforeHolder = reader.getNullable(JsonReader::getLong); - if (notBeforeHolder != null) { - deserializedKeyAttributes.setNotBefore( - OffsetDateTime.ofInstant(Instant.ofEpochSecond(notBeforeHolder), ZoneOffset.UTC)); - } - } else if ("exp".equals(fieldName)) { - Long expiresHolder = reader.getNullable(JsonReader::getLong); - if (expiresHolder != null) { - deserializedKeyAttributes - .setExpires(OffsetDateTime.ofInstant(Instant.ofEpochSecond(expiresHolder), ZoneOffset.UTC)); - } - } else if ("created".equals(fieldName)) { - deserializedKeyAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedKeyAttributes.updated = reader.getNullable(JsonReader::getLong); - } else if ("recoverableDays".equals(fieldName)) { - deserializedKeyAttributes.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("recoveryLevel".equals(fieldName)) { - deserializedKeyAttributes.recoveryLevel = DeletionRecoveryLevel.fromString(reader.getString()); - } else if ("exportable".equals(fieldName)) { - deserializedKeyAttributes.exportable = reader.getNullable(JsonReader::getBoolean); - } else if ("hsmPlatform".equals(fieldName)) { - deserializedKeyAttributes.hsmPlatform = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java deleted file mode 100644 index ca2eb19b893a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * A KeyBundle consisting of a WebKey plus its attributes. - */ -@Fluent -public class KeyBundle implements JsonSerializable { - /* - * The Json web key. - */ - private JsonWebKey key; - - /* - * The key management attributes. - */ - private KeyAttributes attributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be - * true. - */ - private Boolean managed; - - /* - * The policy rules under which the key can be exported. - */ - private KeyReleasePolicy releasePolicy; - - /** - * Creates an instance of KeyBundle class. - */ - public KeyBundle() { - } - - /** - * Get the key property: The Json web key. - * - * @return the key value. - */ - public JsonWebKey getKey() { - return this.key; - } - - /** - * Set the key property: The Json web key. - * - * @param key the key value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setKey(JsonWebKey key) { - this.key = key; - return this; - } - - /** - * Get the attributes property: The key management attributes. - * - * @return the attributes value. - */ - public KeyAttributes getAttributes() { - return this.attributes; - } - - /** - * Set the attributes property: The key management attributes. - * - * @param attributes the attributes value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setAttributes(KeyAttributes attributes) { - this.attributes = attributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Set the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the KeyBundle object itself. - */ - KeyBundle setManaged(Boolean managed) { - this.managed = managed; - return this; - } - - /** - * Get the releasePolicy property: The policy rules under which the key can be exported. - * - * @return the releasePolicy value. - */ - public KeyReleasePolicy getReleasePolicy() { - return this.releasePolicy; - } - - /** - * Set the releasePolicy property: The policy rules under which the key can be exported. - * - * @param releasePolicy the releasePolicy value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("key", this.key); - jsonWriter.writeJsonField("attributes", this.attributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("release_policy", this.releasePolicy); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyBundle from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyBundle if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. - * @throws IOException If an error occurs while reading the KeyBundle. - */ - public static KeyBundle fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyBundle deserializedKeyBundle = new KeyBundle(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("key".equals(fieldName)) { - deserializedKeyBundle.key = JsonWebKey.fromJson(reader); - } else if ("attributes".equals(fieldName)) { - deserializedKeyBundle.attributes = KeyAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyBundle.tags = tags; - } else if ("managed".equals(fieldName)) { - deserializedKeyBundle.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("release_policy".equals(fieldName)) { - deserializedKeyBundle.releasePolicy = KeyReleasePolicy.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyBundle; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java deleted file mode 100644 index a01382b38fd9..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyOperation; -import com.azure.security.keyvault.keys.models.KeyType; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * The key create parameters. - */ -@Fluent -public final class KeyCreateParameters implements JsonSerializable { - /* - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ - private KeyType kty; - - /* - * The key size in bits. For example: 2048, 3072, or 4096 for RSA. - */ - private Integer keySize; - - /* - * The public exponent for a RSA key. - */ - private Integer publicExponent; - - /* - * The key_ops property. - */ - private List keyOps; - - /* - * The attributes of a key managed by the key vault service. - */ - private KeyAttributes keyAttributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * Elliptic curve name. - */ - private KeyCurveName crv; - - /* - * The policy rules under which the key can be exported. - */ - private KeyReleasePolicy releasePolicy; - - /** - * Creates an instance of KeyCreateParameters class. - */ - public KeyCreateParameters() { - } - - /** - * Get the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @return the kty value. - */ - public KeyType getKty() { - return this.kty; - } - - /** - * Set the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @param kty the kty value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setKty(KeyType kty) { - this.kty = kty; - return this; - } - - /** - * Get the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * - * @return the keySize value. - */ - public Integer getKeySize() { - return this.keySize; - } - - /** - * Set the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * - * @param keySize the keySize value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setKeySize(Integer keySize) { - this.keySize = keySize; - return this; - } - - /** - * Get the publicExponent property: The public exponent for a RSA key. - * - * @return the publicExponent value. - */ - public Integer getPublicExponent() { - return this.publicExponent; - } - - /** - * Set the publicExponent property: The public exponent for a RSA key. - * - * @param publicExponent the publicExponent value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setPublicExponent(Integer publicExponent) { - this.publicExponent = publicExponent; - return this; - } - - /** - * Get the keyOps property: The key_ops property. - * - * @return the keyOps value. - */ - public List getKeyOps() { - return this.keyOps; - } - - /** - * Set the keyOps property: The key_ops property. - * - * @param keyOps the keyOps value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setKeyOps(List keyOps) { - this.keyOps = keyOps; - return this; - } - - /** - * Get the keyAttributes property: The attributes of a key managed by the key vault service. - * - * @return the keyAttributes value. - */ - public KeyAttributes getKeyAttributes() { - return this.keyAttributes; - } - - /** - * Set the keyAttributes property: The attributes of a key managed by the key vault service. - * - * @param keyAttributes the keyAttributes value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setKeyAttributes(KeyAttributes keyAttributes) { - this.keyAttributes = keyAttributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the crv property: Elliptic curve name. - * - * @return the crv value. - */ - public KeyCurveName getCrv() { - return this.crv; - } - - /** - * Set the crv property: Elliptic curve name. - * - * @param crv the crv value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setCrv(KeyCurveName crv) { - this.crv = crv; - return this; - } - - /** - * Get the releasePolicy property: The policy rules under which the key can be exported. - * - * @return the releasePolicy value. - */ - public KeyReleasePolicy getReleasePolicy() { - return this.releasePolicy; - } - - /** - * Set the releasePolicy property: The policy rules under which the key can be exported. - * - * @param releasePolicy the releasePolicy value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kty", this.kty == null ? null : this.kty.toString()); - jsonWriter.writeNumberField("key_size", this.keySize); - jsonWriter.writeNumberField("public_exponent", this.publicExponent); - jsonWriter.writeArrayField("key_ops", this.keyOps, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeJsonField("attributes", this.keyAttributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("crv", this.crv == null ? null : this.crv.toString()); - jsonWriter.writeJsonField("release_policy", this.releasePolicy); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyCreateParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyCreateParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeyCreateParameters. - */ - public static KeyCreateParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyCreateParameters deserializedKeyCreateParameters = new KeyCreateParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kty".equals(fieldName)) { - deserializedKeyCreateParameters.kty = KeyType.fromString(reader.getString()); - } else if ("key_size".equals(fieldName)) { - deserializedKeyCreateParameters.keySize = reader.getNullable(JsonReader::getInt); - } else if ("public_exponent".equals(fieldName)) { - deserializedKeyCreateParameters.publicExponent = reader.getNullable(JsonReader::getInt); - } else if ("key_ops".equals(fieldName)) { - List keyOps - = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); - deserializedKeyCreateParameters.keyOps = keyOps; - } else if ("attributes".equals(fieldName)) { - deserializedKeyCreateParameters.keyAttributes = KeyAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyCreateParameters.tags = tags; - } else if ("crv".equals(fieldName)) { - deserializedKeyCreateParameters.crv = KeyCurveName.fromString(reader.getString()); - } else if ("release_policy".equals(fieldName)) { - deserializedKeyCreateParameters.releasePolicy = KeyReleasePolicy.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyCreateParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java deleted file mode 100644 index 97533a27ac5b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; -import java.io.IOException; - -/** - * The export key parameters. - */ -@Fluent -public final class KeyExportParameters implements JsonSerializable { - /* - * The export key encryption Json web key. This key MUST be a RSA key that supports encryption. - */ - private JsonWebKey wrappingKey; - - /* - * The export key encryption key identifier. This key MUST be a RSA key that supports encryption. - */ - private String wrappingKid; - - /* - * The encryption algorithm to use to protected the exported key material - */ - private KeyExportEncryptionAlgorithm enc; - - /** - * Creates an instance of KeyExportParameters class. - */ - public KeyExportParameters() { - } - - /** - * Get the wrappingKey property: The export key encryption Json web key. This key MUST be a RSA key that supports - * encryption. - * - * @return the wrappingKey value. - */ - public JsonWebKey getWrappingKey() { - return this.wrappingKey; - } - - /** - * Set the wrappingKey property: The export key encryption Json web key. This key MUST be a RSA key that supports - * encryption. - * - * @param wrappingKey the wrappingKey value to set. - * @return the KeyExportParameters object itself. - */ - public KeyExportParameters setWrappingKey(JsonWebKey wrappingKey) { - this.wrappingKey = wrappingKey; - return this; - } - - /** - * Get the wrappingKid property: The export key encryption key identifier. This key MUST be a RSA key that supports - * encryption. - * - * @return the wrappingKid value. - */ - public String getWrappingKid() { - return this.wrappingKid; - } - - /** - * Set the wrappingKid property: The export key encryption key identifier. This key MUST be a RSA key that supports - * encryption. - * - * @param wrappingKid the wrappingKid value to set. - * @return the KeyExportParameters object itself. - */ - public KeyExportParameters setWrappingKid(String wrappingKid) { - this.wrappingKid = wrappingKid; - return this; - } - - /** - * Get the enc property: The encryption algorithm to use to protected the exported key material. - * - * @return the enc value. - */ - public KeyExportEncryptionAlgorithm getEnc() { - return this.enc; - } - - /** - * Set the enc property: The encryption algorithm to use to protected the exported key material. - * - * @param enc the enc value to set. - * @return the KeyExportParameters object itself. - */ - public KeyExportParameters setEnc(KeyExportEncryptionAlgorithm enc) { - this.enc = enc; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("wrappingKey", this.wrappingKey); - jsonWriter.writeStringField("wrappingKid", this.wrappingKid); - jsonWriter.writeStringField("enc", this.enc == null ? null : this.enc.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyExportParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyExportParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyExportParameters. - */ - public static KeyExportParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyExportParameters deserializedKeyExportParameters = new KeyExportParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("wrappingKey".equals(fieldName)) { - deserializedKeyExportParameters.wrappingKey = JsonWebKey.fromJson(reader); - } else if ("wrappingKid".equals(fieldName)) { - deserializedKeyExportParameters.wrappingKid = reader.getString(); - } else if ("enc".equals(fieldName)) { - deserializedKeyExportParameters.enc = KeyExportEncryptionAlgorithm.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyExportParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java deleted file mode 100644 index 35bd87eb23ef..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * The key import parameters. - */ -@Fluent -public final class KeyImportParameters implements JsonSerializable { - /* - * Whether to import as a hardware key (HSM) or software key. - */ - private Boolean hsm; - - /* - * The Json web key - */ - private JsonWebKey key; - - /* - * The key management attributes. - */ - private KeyAttributes keyAttributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * The policy rules under which the key can be exported. - */ - private KeyReleasePolicy releasePolicy; - - /** - * Creates an instance of KeyImportParameters class. - */ - public KeyImportParameters() { - } - - /** - * Get the hsm property: Whether to import as a hardware key (HSM) or software key. - * - * @return the hsm value. - */ - public Boolean isHsm() { - return this.hsm; - } - - /** - * Set the hsm property: Whether to import as a hardware key (HSM) or software key. - * - * @param hsm the hsm value to set. - * @return the KeyImportParameters object itself. - */ - public KeyImportParameters setHsm(Boolean hsm) { - this.hsm = hsm; - return this; - } - - /** - * Get the key property: The Json web key. - * - * @return the key value. - */ - public JsonWebKey getKey() { - return this.key; - } - - /** - * Set the key property: The Json web key. - * - * @param key the key value to set. - * @return the KeyImportParameters object itself. - */ - public KeyImportParameters setKey(JsonWebKey key) { - this.key = key; - return this; - } - - /** - * Get the keyAttributes property: The key management attributes. - * - * @return the keyAttributes value. - */ - public KeyAttributes getKeyAttributes() { - return this.keyAttributes; - } - - /** - * Set the keyAttributes property: The key management attributes. - * - * @param keyAttributes the keyAttributes value to set. - * @return the KeyImportParameters object itself. - */ - public KeyImportParameters setKeyAttributes(KeyAttributes keyAttributes) { - this.keyAttributes = keyAttributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyImportParameters object itself. - */ - public KeyImportParameters setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the releasePolicy property: The policy rules under which the key can be exported. - * - * @return the releasePolicy value. - */ - public KeyReleasePolicy getReleasePolicy() { - return this.releasePolicy; - } - - /** - * Set the releasePolicy property: The policy rules under which the key can be exported. - * - * @param releasePolicy the releasePolicy value to set. - * @return the KeyImportParameters object itself. - */ - public KeyImportParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("key", this.key); - jsonWriter.writeBooleanField("Hsm", this.hsm); - jsonWriter.writeJsonField("attributes", this.keyAttributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("release_policy", this.releasePolicy); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyImportParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyImportParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeyImportParameters. - */ - public static KeyImportParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyImportParameters deserializedKeyImportParameters = new KeyImportParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("key".equals(fieldName)) { - deserializedKeyImportParameters.key = JsonWebKey.fromJson(reader); - } else if ("Hsm".equals(fieldName)) { - deserializedKeyImportParameters.hsm = reader.getNullable(JsonReader::getBoolean); - } else if ("attributes".equals(fieldName)) { - deserializedKeyImportParameters.keyAttributes = KeyAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyImportParameters.tags = tags; - } else if ("release_policy".equals(fieldName)) { - deserializedKeyImportParameters.releasePolicy = KeyReleasePolicy.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyImportParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java deleted file mode 100644 index b21d84785ae1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * The key item containing key metadata. - */ -@Fluent -public class KeyItem implements JsonSerializable { - /* - * Key identifier. - */ - private String kid; - - /* - * The key management attributes. - */ - private KeyAttributes attributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be - * true. - */ - private Boolean managed; - - /** - * Creates an instance of KeyItem class. - */ - public KeyItem() { - } - - /** - * Get the kid property: Key identifier. - * - * @return the kid value. - */ - public String getKid() { - return this.kid; - } - - /** - * Set the kid property: Key identifier. - * - * @param kid the kid value to set. - * @return the KeyItem object itself. - */ - public KeyItem setKid(String kid) { - this.kid = kid; - return this; - } - - /** - * Get the attributes property: The key management attributes. - * - * @return the attributes value. - */ - public KeyAttributes getAttributes() { - return this.attributes; - } - - /** - * Set the attributes property: The key management attributes. - * - * @param attributes the attributes value to set. - * @return the KeyItem object itself. - */ - public KeyItem setAttributes(KeyAttributes attributes) { - this.attributes = attributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyItem object itself. - */ - public KeyItem setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Set the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the KeyItem object itself. - */ - KeyItem setManaged(Boolean managed) { - this.managed = managed; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kid", this.kid); - jsonWriter.writeJsonField("attributes", this.attributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyItem from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyItem if the JsonReader was pointing to an instance of it, or null if it was pointing to - * JSON null. - * @throws IOException If an error occurs while reading the KeyItem. - */ - public static KeyItem fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyItem deserializedKeyItem = new KeyItem(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kid".equals(fieldName)) { - deserializedKeyItem.kid = reader.getString(); - } else if ("attributes".equals(fieldName)) { - deserializedKeyItem.attributes = KeyAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyItem.tags = tags; - } else if ("managed".equals(fieldName)) { - deserializedKeyItem.managed = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyItem; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java deleted file mode 100644 index 10787e79d6fd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * The key list result. - */ -@Immutable -public final class KeyListResult implements JsonSerializable { - /* - * A response message containing a list of keys in the key vault along with a link to the next page of keys. - */ - private List value; - - /* - * The URL to get the next set of keys. - */ - private String nextLink; - - /** - * Creates an instance of KeyListResult class. - */ - public KeyListResult() { - } - - /** - * Get the value property: A response message containing a list of keys in the key vault along with a link to the - * next page of keys. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of keys. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyListResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyListResult. - */ - public static KeyListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyListResult deserializedKeyListResult = new KeyListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> KeyItem.fromJson(reader1)); - deserializedKeyListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedKeyListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java deleted file mode 100644 index 4a32c1bc1a9d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.Base64Url; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key operation result. - */ -@Immutable -public final class KeyOperationResult implements JsonSerializable { - /* - * Key identifier - */ - private String kid; - - /* - * The value property. - */ - private Base64Url result; - - /* - * The iv property. - */ - private Base64Url iv; - - /* - * The tag property. - */ - private Base64Url authenticationTag; - - /* - * The aad property. - */ - private Base64Url additionalAuthenticatedData; - - /** - * Creates an instance of KeyOperationResult class. - */ - public KeyOperationResult() { - } - - /** - * Get the kid property: Key identifier. - * - * @return the kid value. - */ - public String getKid() { - return this.kid; - } - - /** - * Get the result property: The value property. - * - * @return the result value. - */ - public byte[] getResult() { - if (this.result == null) { - return null; - } - return this.result.decodedBytes(); - } - - /** - * Get the iv property: The iv property. - * - * @return the iv value. - */ - public byte[] getIv() { - if (this.iv == null) { - return null; - } - return this.iv.decodedBytes(); - } - - /** - * Get the authenticationTag property: The tag property. - * - * @return the authenticationTag value. - */ - public byte[] getAuthenticationTag() { - if (this.authenticationTag == null) { - return null; - } - return this.authenticationTag.decodedBytes(); - } - - /** - * Get the additionalAuthenticatedData property: The aad property. - * - * @return the additionalAuthenticatedData value. - */ - public byte[] getAdditionalAuthenticatedData() { - if (this.additionalAuthenticatedData == null) { - return null; - } - return this.additionalAuthenticatedData.decodedBytes(); - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyOperationResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyOperationResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyOperationResult. - */ - public static KeyOperationResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyOperationResult deserializedKeyOperationResult = new KeyOperationResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kid".equals(fieldName)) { - deserializedKeyOperationResult.kid = reader.getString(); - } else if ("value".equals(fieldName)) { - deserializedKeyOperationResult.result - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("iv".equals(fieldName)) { - deserializedKeyOperationResult.iv - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("tag".equals(fieldName)) { - deserializedKeyOperationResult.authenticationTag - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("aad".equals(fieldName)) { - deserializedKeyOperationResult.additionalAuthenticatedData - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyOperationResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java deleted file mode 100644 index ecb81c28fde7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The key operations parameters. - */ -@Fluent -public final class KeyOperationsParameters implements JsonSerializable { - /* - * algorithm identifier - */ - private JsonWebKeyEncryptionAlgorithm algorithm; - - /* - * The value property. - */ - private Base64Url value; - - /* - * Cryptographically random, non-repeating initialization vector for symmetric algorithms. - */ - private Base64Url iv; - - /* - * Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - */ - private Base64Url aad; - - /* - * The tag to authenticate when performing decryption with an authenticated algorithm. - */ - private Base64Url tag; - - /** - * Creates an instance of KeyOperationsParameters class. - */ - public KeyOperationsParameters() { - } - - /** - * Get the algorithm property: algorithm identifier. - * - * @return the algorithm value. - */ - public JsonWebKeyEncryptionAlgorithm getAlgorithm() { - return this.algorithm; - } - - /** - * Set the algorithm property: algorithm identifier. - * - * @param algorithm the algorithm value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setAlgorithm(JsonWebKeyEncryptionAlgorithm algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Get the value property: The value property. - * - * @return the value value. - */ - public byte[] getValue() { - if (this.value == null) { - return null; - } - return this.value.decodedBytes(); - } - - /** - * Set the value property: The value property. - * - * @param value the value value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setValue(byte[] value) { - if (value == null) { - this.value = null; - } else { - this.value = Base64Url.encode(CoreUtils.clone(value)); - } - return this; - } - - /** - * Get the iv property: Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * - * @return the iv value. - */ - public byte[] getIv() { - if (this.iv == null) { - return null; - } - return this.iv.decodedBytes(); - } - - /** - * Set the iv property: Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * - * @param iv the iv value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setIv(byte[] iv) { - if (iv == null) { - this.iv = null; - } else { - this.iv = Base64Url.encode(CoreUtils.clone(iv)); - } - return this; - } - - /** - * Get the aad property: Additional data to authenticate but not encrypt/decrypt when using authenticated crypto - * algorithms. - * - * @return the aad value. - */ - public byte[] getAad() { - if (this.aad == null) { - return null; - } - return this.aad.decodedBytes(); - } - - /** - * Set the aad property: Additional data to authenticate but not encrypt/decrypt when using authenticated crypto - * algorithms. - * - * @param aad the aad value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setAad(byte[] aad) { - if (aad == null) { - this.aad = null; - } else { - this.aad = Base64Url.encode(CoreUtils.clone(aad)); - } - return this; - } - - /** - * Get the tag property: The tag to authenticate when performing decryption with an authenticated algorithm. - * - * @return the tag value. - */ - public byte[] getTag() { - if (this.tag == null) { - return null; - } - return this.tag.decodedBytes(); - } - - /** - * Set the tag property: The tag to authenticate when performing decryption with an authenticated algorithm. - * - * @param tag the tag value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setTag(byte[] tag) { - if (tag == null) { - this.tag = null; - } else { - this.tag = Base64Url.encode(CoreUtils.clone(tag)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("alg", this.algorithm == null ? null : this.algorithm.toString()); - jsonWriter.writeStringField("value", Objects.toString(this.value, null)); - jsonWriter.writeStringField("iv", Objects.toString(this.iv, null)); - jsonWriter.writeStringField("aad", Objects.toString(this.aad, null)); - jsonWriter.writeStringField("tag", Objects.toString(this.tag, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyOperationsParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyOperationsParameters if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeyOperationsParameters. - */ - public static KeyOperationsParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyOperationsParameters deserializedKeyOperationsParameters = new KeyOperationsParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("alg".equals(fieldName)) { - deserializedKeyOperationsParameters.algorithm - = JsonWebKeyEncryptionAlgorithm.fromString(reader.getString()); - } else if ("value".equals(fieldName)) { - deserializedKeyOperationsParameters.value - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("iv".equals(fieldName)) { - deserializedKeyOperationsParameters.iv - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("aad".equals(fieldName)) { - deserializedKeyOperationsParameters.aad - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("tag".equals(fieldName)) { - deserializedKeyOperationsParameters.tag - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyOperationsParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java deleted file mode 100644 index dba8bf629372..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyType; -import java.io.IOException; - -/** - * Properties of the key pair backing a certificate. - */ -@Fluent -public final class KeyProperties implements JsonSerializable { - /* - * Indicates if the private key can be exported. Release policy must be provided when creating the first version of - * an exportable key. - */ - private Boolean exportable; - - /* - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ - private KeyType kty; - - /* - * The key size in bits. For example: 2048, 3072, or 4096 for RSA. - */ - private Integer keySize; - - /* - * Indicates if the same key pair will be used on certificate renewal. - */ - private Boolean reuseKey; - - /* - * Elliptic curve name. - */ - private KeyCurveName crv; - - /** - * Creates an instance of KeyProperties class. - */ - public KeyProperties() { - } - - /** - * Get the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @return the exportable value. - */ - public Boolean isExportable() { - return this.exportable; - } - - /** - * Set the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @param exportable the exportable value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setExportable(Boolean exportable) { - this.exportable = exportable; - return this; - } - - /** - * Get the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @return the kty value. - */ - public KeyType getKty() { - return this.kty; - } - - /** - * Set the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @param kty the kty value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setKty(KeyType kty) { - this.kty = kty; - return this; - } - - /** - * Get the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * - * @return the keySize value. - */ - public Integer getKeySize() { - return this.keySize; - } - - /** - * Set the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * - * @param keySize the keySize value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setKeySize(Integer keySize) { - this.keySize = keySize; - return this; - } - - /** - * Get the reuseKey property: Indicates if the same key pair will be used on certificate renewal. - * - * @return the reuseKey value. - */ - public Boolean isReuseKey() { - return this.reuseKey; - } - - /** - * Set the reuseKey property: Indicates if the same key pair will be used on certificate renewal. - * - * @param reuseKey the reuseKey value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setReuseKey(Boolean reuseKey) { - this.reuseKey = reuseKey; - return this; - } - - /** - * Get the crv property: Elliptic curve name. - * - * @return the crv value. - */ - public KeyCurveName getCrv() { - return this.crv; - } - - /** - * Set the crv property: Elliptic curve name. - * - * @param crv the crv value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setCrv(KeyCurveName crv) { - this.crv = crv; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("exportable", this.exportable); - jsonWriter.writeStringField("kty", this.kty == null ? null : this.kty.toString()); - jsonWriter.writeNumberField("key_size", this.keySize); - jsonWriter.writeBooleanField("reuse_key", this.reuseKey); - jsonWriter.writeStringField("crv", this.crv == null ? null : this.crv.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyProperties if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyProperties. - */ - public static KeyProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyProperties deserializedKeyProperties = new KeyProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("exportable".equals(fieldName)) { - deserializedKeyProperties.exportable = reader.getNullable(JsonReader::getBoolean); - } else if ("kty".equals(fieldName)) { - deserializedKeyProperties.kty = KeyType.fromString(reader.getString()); - } else if ("key_size".equals(fieldName)) { - deserializedKeyProperties.keySize = reader.getNullable(JsonReader::getInt); - } else if ("reuse_key".equals(fieldName)) { - deserializedKeyProperties.reuseKey = reader.getNullable(JsonReader::getBoolean); - } else if ("crv".equals(fieldName)) { - deserializedKeyProperties.crv = KeyCurveName.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyProperties; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java deleted file mode 100644 index c11dd6fecbb4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; -import java.io.IOException; - -/** - * The release key parameters. - */ -@Fluent -public final class KeyReleaseParameters implements JsonSerializable { - /* - * The attestation assertion for the target of the key release. - */ - private String targetAttestationToken; - - /* - * A client provided nonce for freshness. - */ - private String nonce; - - /* - * The encryption algorithm to use to protected the exported key material - */ - private KeyExportEncryptionAlgorithm enc; - - /** - * Creates an instance of KeyReleaseParameters class. - */ - public KeyReleaseParameters() { - } - - /** - * Get the targetAttestationToken property: The attestation assertion for the target of the key release. - * - * @return the targetAttestationToken value. - */ - public String getTargetAttestationToken() { - return this.targetAttestationToken; - } - - /** - * Set the targetAttestationToken property: The attestation assertion for the target of the key release. - * - * @param targetAttestationToken the targetAttestationToken value to set. - * @return the KeyReleaseParameters object itself. - */ - public KeyReleaseParameters setTargetAttestationToken(String targetAttestationToken) { - this.targetAttestationToken = targetAttestationToken; - return this; - } - - /** - * Get the nonce property: A client provided nonce for freshness. - * - * @return the nonce value. - */ - public String getNonce() { - return this.nonce; - } - - /** - * Set the nonce property: A client provided nonce for freshness. - * - * @param nonce the nonce value to set. - * @return the KeyReleaseParameters object itself. - */ - public KeyReleaseParameters setNonce(String nonce) { - this.nonce = nonce; - return this; - } - - /** - * Get the enc property: The encryption algorithm to use to protected the exported key material. - * - * @return the enc value. - */ - public KeyExportEncryptionAlgorithm getEnc() { - return this.enc; - } - - /** - * Set the enc property: The encryption algorithm to use to protected the exported key material. - * - * @param enc the enc value to set. - * @return the KeyReleaseParameters object itself. - */ - public KeyReleaseParameters setEnc(KeyExportEncryptionAlgorithm enc) { - this.enc = enc; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("target", this.targetAttestationToken); - jsonWriter.writeStringField("nonce", this.nonce); - jsonWriter.writeStringField("enc", this.enc == null ? null : this.enc.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyReleaseParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyReleaseParameters if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeyReleaseParameters. - */ - public static KeyReleaseParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyReleaseParameters deserializedKeyReleaseParameters = new KeyReleaseParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("target".equals(fieldName)) { - deserializedKeyReleaseParameters.targetAttestationToken = reader.getString(); - } else if ("nonce".equals(fieldName)) { - deserializedKeyReleaseParameters.nonce = reader.getString(); - } else if ("enc".equals(fieldName)) { - deserializedKeyReleaseParameters.enc = KeyExportEncryptionAlgorithm.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyReleaseParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java deleted file mode 100644 index c5de807bce69..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The policy rules under which the key can be exported. - */ -@Fluent -public final class KeyReleasePolicy implements JsonSerializable { - /* - * Content type and version of key release policy - */ - private String contentType; - - /* - * Defines the mutability state of the policy. Once marked immutable, this flag cannot be reset and the policy - * cannot be changed under any circumstances. - */ - private Boolean immutable; - - /* - * Blob encoding the policy rules under which the key can be released. Blob must be base64 URL encoded. - */ - private Base64Url encodedPolicy; - - /** - * Creates an instance of KeyReleasePolicy class. - */ - public KeyReleasePolicy() { - } - - /** - * Get the contentType property: Content type and version of key release policy. - * - * @return the contentType value. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType property: Content type and version of key release policy. - * - * @param contentType the contentType value to set. - * @return the KeyReleasePolicy object itself. - */ - public KeyReleasePolicy setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Get the immutable property: Defines the mutability state of the policy. Once marked immutable, this flag cannot - * be reset and the policy cannot be changed under any circumstances. - * - * @return the immutable value. - */ - public Boolean isImmutable() { - return this.immutable; - } - - /** - * Set the immutable property: Defines the mutability state of the policy. Once marked immutable, this flag cannot - * be reset and the policy cannot be changed under any circumstances. - * - * @param immutable the immutable value to set. - * @return the KeyReleasePolicy object itself. - */ - public KeyReleasePolicy setImmutable(Boolean immutable) { - this.immutable = immutable; - return this; - } - - /** - * Get the encodedPolicy property: Blob encoding the policy rules under which the key can be released. Blob must be - * base64 URL encoded. - * - * @return the encodedPolicy value. - */ - public byte[] getEncodedPolicy() { - if (this.encodedPolicy == null) { - return null; - } - return this.encodedPolicy.decodedBytes(); - } - - /** - * Set the encodedPolicy property: Blob encoding the policy rules under which the key can be released. Blob must be - * base64 URL encoded. - * - * @param encodedPolicy the encodedPolicy value to set. - * @return the KeyReleasePolicy object itself. - */ - public KeyReleasePolicy setEncodedPolicy(byte[] encodedPolicy) { - if (encodedPolicy == null) { - this.encodedPolicy = null; - } else { - this.encodedPolicy = Base64Url.encode(CoreUtils.clone(encodedPolicy)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("contentType", this.contentType); - jsonWriter.writeBooleanField("immutable", this.immutable); - jsonWriter.writeStringField("data", Objects.toString(this.encodedPolicy, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyReleasePolicy from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyReleasePolicy if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyReleasePolicy. - */ - public static KeyReleasePolicy fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyReleasePolicy deserializedKeyReleasePolicy = new KeyReleasePolicy(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("contentType".equals(fieldName)) { - deserializedKeyReleasePolicy.contentType = reader.getString(); - } else if ("immutable".equals(fieldName)) { - deserializedKeyReleasePolicy.immutable = reader.getNullable(JsonReader::getBoolean); - } else if ("data".equals(fieldName)) { - deserializedKeyReleasePolicy.encodedPolicy - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyReleasePolicy; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java deleted file mode 100644 index 720b708c6769..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The key restore parameters. - */ -@Fluent -public final class KeyRestoreParameters implements JsonSerializable { - /* - * The backup blob associated with a key bundle. - */ - private Base64Url keyBundleBackup; - - /** - * Creates an instance of KeyRestoreParameters class. - */ - public KeyRestoreParameters() { - } - - /** - * Get the keyBundleBackup property: The backup blob associated with a key bundle. - * - * @return the keyBundleBackup value. - */ - public byte[] getKeyBundleBackup() { - if (this.keyBundleBackup == null) { - return null; - } - return this.keyBundleBackup.decodedBytes(); - } - - /** - * Set the keyBundleBackup property: The backup blob associated with a key bundle. - * - * @param keyBundleBackup the keyBundleBackup value to set. - * @return the KeyRestoreParameters object itself. - */ - public KeyRestoreParameters setKeyBundleBackup(byte[] keyBundleBackup) { - if (keyBundleBackup == null) { - this.keyBundleBackup = null; - } else { - this.keyBundleBackup = Base64Url.encode(CoreUtils.clone(keyBundleBackup)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", Objects.toString(this.keyBundleBackup, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyRestoreParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyRestoreParameters if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeyRestoreParameters. - */ - public static KeyRestoreParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyRestoreParameters deserializedKeyRestoreParameters = new KeyRestoreParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedKeyRestoreParameters.keyBundleBackup - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyRestoreParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java deleted file mode 100644 index d6e6b7517cc2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * Management policy for a key. - */ -@Fluent -public final class KeyRotationPolicy implements JsonSerializable { - /* - * The key policy id. - */ - private String id; - - /* - * Actions that will be performed by Key Vault over the lifetime of a key. For preview, lifetimeActions can only - * have two items at maximum: one for rotate, one for notify. Notification time would be default to 30 days before - * expiry and it is not configurable. - */ - private List lifetimeActions; - - /* - * The key rotation policy attributes. - */ - private KeyRotationPolicyAttributes attributes; - - /** - * Creates an instance of KeyRotationPolicy class. - */ - public KeyRotationPolicy() { - } - - /** - * Get the id property: The key policy id. - * - * @return the id value. - */ - public String getId() { - return this.id; - } - - /** - * Get the lifetimeActions property: Actions that will be performed by Key Vault over the lifetime of a key. For - * preview, lifetimeActions can only have two items at maximum: one for rotate, one for notify. Notification time - * would be default to 30 days before expiry and it is not configurable. - * - * @return the lifetimeActions value. - */ - public List getLifetimeActions() { - return this.lifetimeActions; - } - - /** - * Set the lifetimeActions property: Actions that will be performed by Key Vault over the lifetime of a key. For - * preview, lifetimeActions can only have two items at maximum: one for rotate, one for notify. Notification time - * would be default to 30 days before expiry and it is not configurable. - * - * @param lifetimeActions the lifetimeActions value to set. - * @return the KeyRotationPolicy object itself. - */ - public KeyRotationPolicy setLifetimeActions(List lifetimeActions) { - this.lifetimeActions = lifetimeActions; - return this; - } - - /** - * Get the attributes property: The key rotation policy attributes. - * - * @return the attributes value. - */ - public KeyRotationPolicyAttributes getAttributes() { - return this.attributes; - } - - /** - * Set the attributes property: The key rotation policy attributes. - * - * @param attributes the attributes value to set. - * @return the KeyRotationPolicy object itself. - */ - public KeyRotationPolicy setAttributes(KeyRotationPolicyAttributes attributes) { - this.attributes = attributes; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("lifetimeActions", this.lifetimeActions, - (writer, element) -> writer.writeJson(element)); - jsonWriter.writeJsonField("attributes", this.attributes); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyRotationPolicy from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyRotationPolicy if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyRotationPolicy. - */ - public static KeyRotationPolicy fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyRotationPolicy deserializedKeyRotationPolicy = new KeyRotationPolicy(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedKeyRotationPolicy.id = reader.getString(); - } else if ("lifetimeActions".equals(fieldName)) { - List lifetimeActions - = reader.readArray(reader1 -> LifetimeActions.fromJson(reader1)); - deserializedKeyRotationPolicy.lifetimeActions = lifetimeActions; - } else if ("attributes".equals(fieldName)) { - deserializedKeyRotationPolicy.attributes = KeyRotationPolicyAttributes.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyRotationPolicy; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java deleted file mode 100644 index b9cfc05d6253..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The key rotation policy attributes. - */ -@Fluent -public final class KeyRotationPolicyAttributes implements JsonSerializable { - /* - * The expiryTime will be applied on the new key version. It should be at least 28 days. It will be in ISO 8601 - * Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: P1Y10D - */ - private String expiryTime; - - /* - * The key rotation policy created time in UTC. - */ - private Long created; - - /* - * The key rotation policy's last updated time in UTC. - */ - private Long updated; - - /** - * Creates an instance of KeyRotationPolicyAttributes class. - */ - public KeyRotationPolicyAttributes() { - } - - /** - * Get the expiryTime property: The expiryTime will be applied on the new key version. It should be at least 28 - * days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: - * P1Y10D. - * - * @return the expiryTime value. - */ - public String getExpiryTime() { - return this.expiryTime; - } - - /** - * Set the expiryTime property: The expiryTime will be applied on the new key version. It should be at least 28 - * days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: - * P1Y10D. - * - * @param expiryTime the expiryTime value to set. - * @return the KeyRotationPolicyAttributes object itself. - */ - public KeyRotationPolicyAttributes setExpiryTime(String expiryTime) { - this.expiryTime = expiryTime; - return this; - } - - /** - * Get the created property: The key rotation policy created time in UTC. - * - * @return the created value. - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * Get the updated property: The key rotation policy's last updated time in UTC. - * - * @return the updated value. - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("expiryTime", this.expiryTime); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyRotationPolicyAttributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyRotationPolicyAttributes if the JsonReader was pointing to an instance of it, or null - * if it was pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyRotationPolicyAttributes. - */ - public static KeyRotationPolicyAttributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyRotationPolicyAttributes deserializedKeyRotationPolicyAttributes = new KeyRotationPolicyAttributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("expiryTime".equals(fieldName)) { - deserializedKeyRotationPolicyAttributes.expiryTime = reader.getString(); - } else if ("created".equals(fieldName)) { - deserializedKeyRotationPolicyAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedKeyRotationPolicyAttributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyRotationPolicyAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java deleted file mode 100644 index fb149d41690a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The key operations parameters. - */ -@Fluent -public final class KeySignParameters implements JsonSerializable { - /* - * The signing/verification algorithm identifier. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - */ - private JsonWebKeySignatureAlgorithm algorithm; - - /* - * The value property. - */ - private Base64Url value; - - /** - * Creates an instance of KeySignParameters class. - */ - public KeySignParameters() { - } - - /** - * Get the algorithm property: The signing/verification algorithm identifier. For more information on possible - * algorithm types, see JsonWebKeySignatureAlgorithm. - * - * @return the algorithm value. - */ - public JsonWebKeySignatureAlgorithm getAlgorithm() { - return this.algorithm; - } - - /** - * Set the algorithm property: The signing/verification algorithm identifier. For more information on possible - * algorithm types, see JsonWebKeySignatureAlgorithm. - * - * @param algorithm the algorithm value to set. - * @return the KeySignParameters object itself. - */ - public KeySignParameters setAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Get the value property: The value property. - * - * @return the value value. - */ - public byte[] getValue() { - if (this.value == null) { - return null; - } - return this.value.decodedBytes(); - } - - /** - * Set the value property: The value property. - * - * @param value the value value to set. - * @return the KeySignParameters object itself. - */ - public KeySignParameters setValue(byte[] value) { - if (value == null) { - this.value = null; - } else { - this.value = Base64Url.encode(CoreUtils.clone(value)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("alg", this.algorithm == null ? null : this.algorithm.toString()); - jsonWriter.writeStringField("value", Objects.toString(this.value, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeySignParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeySignParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeySignParameters. - */ - public static KeySignParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeySignParameters deserializedKeySignParameters = new KeySignParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("alg".equals(fieldName)) { - deserializedKeySignParameters.algorithm - = JsonWebKeySignatureAlgorithm.fromString(reader.getString()); - } else if ("value".equals(fieldName)) { - deserializedKeySignParameters.value - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedKeySignParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java deleted file mode 100644 index 16aa11c86eaf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyOperation; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * The key update parameters. - */ -@Fluent -public final class KeyUpdateParameters implements JsonSerializable { - /* - * Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - */ - private List keyOps; - - /* - * The attributes of a key managed by the key vault service. - */ - private KeyAttributes keyAttributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * The policy rules under which the key can be exported. - */ - private KeyReleasePolicy releasePolicy; - - /** - * Creates an instance of KeyUpdateParameters class. - */ - public KeyUpdateParameters() { - } - - /** - * Get the keyOps property: Json web key operations. For more information on possible key operations, see - * JsonWebKeyOperation. - * - * @return the keyOps value. - */ - public List getKeyOps() { - return this.keyOps; - } - - /** - * Set the keyOps property: Json web key operations. For more information on possible key operations, see - * JsonWebKeyOperation. - * - * @param keyOps the keyOps value to set. - * @return the KeyUpdateParameters object itself. - */ - public KeyUpdateParameters setKeyOps(List keyOps) { - this.keyOps = keyOps; - return this; - } - - /** - * Get the keyAttributes property: The attributes of a key managed by the key vault service. - * - * @return the keyAttributes value. - */ - public KeyAttributes getKeyAttributes() { - return this.keyAttributes; - } - - /** - * Set the keyAttributes property: The attributes of a key managed by the key vault service. - * - * @param keyAttributes the keyAttributes value to set. - * @return the KeyUpdateParameters object itself. - */ - public KeyUpdateParameters setKeyAttributes(KeyAttributes keyAttributes) { - this.keyAttributes = keyAttributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyUpdateParameters object itself. - */ - public KeyUpdateParameters setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the releasePolicy property: The policy rules under which the key can be exported. - * - * @return the releasePolicy value. - */ - public KeyReleasePolicy getReleasePolicy() { - return this.releasePolicy; - } - - /** - * Set the releasePolicy property: The policy rules under which the key can be exported. - * - * @param releasePolicy the releasePolicy value to set. - * @return the KeyUpdateParameters object itself. - */ - public KeyUpdateParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("key_ops", this.keyOps, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeJsonField("attributes", this.keyAttributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("release_policy", this.releasePolicy); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyUpdateParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyUpdateParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyUpdateParameters. - */ - public static KeyUpdateParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyUpdateParameters deserializedKeyUpdateParameters = new KeyUpdateParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("key_ops".equals(fieldName)) { - List keyOps - = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); - deserializedKeyUpdateParameters.keyOps = keyOps; - } else if ("attributes".equals(fieldName)) { - deserializedKeyUpdateParameters.keyAttributes = KeyAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyUpdateParameters.tags = tags; - } else if ("release_policy".equals(fieldName)) { - deserializedKeyUpdateParameters.releasePolicy = KeyReleasePolicy.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyUpdateParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java deleted file mode 100644 index 878f44cec3d8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key vault error exception. - */ -@Immutable -public final class KeyVaultError implements JsonSerializable { - /* - * The key vault server error. - */ - private Error error; - - /** - * Creates an instance of KeyVaultError class. - */ - public KeyVaultError() { - } - - /** - * Get the error property: The key vault server error. - * - * @return the error value. - */ - public Error getError() { - return this.error; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVaultError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVaultError if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyVaultError. - */ - public static KeyVaultError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultError deserializedKeyVaultError = new KeyVaultError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedKeyVaultError.error = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVaultError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java deleted file mode 100644 index 43c502fea680..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with KeyVaultError information. - */ -public final class KeyVaultErrorException extends HttpResponseException { - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public KeyVaultErrorException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - * @param value the deserialized response value. - */ - public KeyVaultErrorException(String message, HttpResponse response, KeyVaultError value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyVaultError getValue() { - return (KeyVaultError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java deleted file mode 100644 index 032031292487..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.util.BinaryData; -import com.azure.core.util.CoreUtils; -import com.azure.security.keyvault.keys.implementation.DeletedKeyHelper; -import com.azure.security.keyvault.keys.implementation.KeyPropertiesHelper; -import com.azure.security.keyvault.keys.implementation.KeyRotationPolicyHelper; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeyHelper; -import com.azure.security.keyvault.keys.models.CreateKeyOptions; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyProperties; -import com.azure.security.keyvault.keys.models.KeyReleasePolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyVaultKey; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Objects; -import java.util.function.Consumer; - -/** - * Utility class for KeyVault Keys models. - */ -public final class KeyVaultKeysModelsUtils { - public static KeyVaultKey createKeyVaultKey(KeyBundle keyBundle) { - if (keyBundle == null) { - return null; - } - - KeyVaultKey keyVaultKey = KeyVaultKeyHelper.createKeyVaultKey(mapJsonWebKeyFromImpl(keyBundle.getKey())); - populateKeyProperties(keyBundle, keyVaultKey.getProperties()); - - return keyVaultKey; - } - - public static KeyProperties createKeyProperties(KeyItem keyItem) { - if (keyItem == null) { - return null; - } - - KeyProperties properties = new KeyProperties(); - populateKeyProperties(keyItem, properties); - - return properties; - } - - private static void populateKeyProperties(KeyItem keyItem, KeyProperties properties) { - if (keyItem == null) { - return; - } - - properties.setTags(keyItem.getTags()); - KeyPropertiesHelper.setManaged(properties, keyItem.isManaged()); - KeyPropertiesHelper.setId(properties, keyItem.getKid()); - - unpackId(keyItem.getKid(), name -> KeyPropertiesHelper.setName(properties, name), - version -> KeyPropertiesHelper.setVersion(properties, version)); - - KeyAttributes attributes = keyItem.getAttributes(); - if (attributes != null) { - properties.setEnabled(attributes.isEnabled()) - .setExpiresOn(attributes.getExpires()) - .setExportable(attributes.isExportable()) - .setNotBefore(attributes.getNotBefore()); - - KeyPropertiesHelper.setCreatedOn(properties, attributes.getCreated()); - KeyPropertiesHelper.setUpdatedOn(properties, attributes.getUpdated()); - KeyPropertiesHelper.setRecoveryLevel(properties, Objects.toString(attributes.getRecoveryLevel(), null)); - KeyPropertiesHelper.setRecoverableDays(properties, attributes.getRecoverableDays()); - KeyPropertiesHelper.setHsmPlatform(properties, attributes.getHsmPlatform()); - } - } - - public static DeletedKey createDeletedKey(DeletedKeyBundle bundle) { - if (bundle == null) { - return null; - } - - DeletedKey deletedKey = DeletedKeyHelper.createDeletedKey(mapJsonWebKeyFromImpl(bundle.getKey())); - populateKeyProperties(bundle, deletedKey.getProperties()); - - DeletedKeyHelper.setRecoveryId(deletedKey, bundle.getRecoveryId()); - DeletedKeyHelper.setScheduledPurgeDate(deletedKey, bundle.getScheduledPurgeDate()); - DeletedKeyHelper.setDeletedOn(deletedKey, bundle.getDeletedDate()); - - return deletedKey; - } - - public static DeletedKey createDeletedKey(DeletedKeyItem item) { - if (item == null) { - return null; - } - - DeletedKey deletedKey = new DeletedKey(); - populateKeyProperties(item, deletedKey.getProperties()); - - DeletedKeyHelper.setRecoveryId(deletedKey, item.getRecoveryId()); - DeletedKeyHelper.setDeletedOn(deletedKey, item.getDeletedDate()); - DeletedKeyHelper.setScheduledPurgeDate(deletedKey, item.getScheduledPurgeDate()); - - return deletedKey; - } - - private static JsonWebKey - mapJsonWebKeyFromImpl(com.azure.security.keyvault.keys.implementation.models.JsonWebKey impl) { - if (impl == null) { - return null; - } - - return new JsonWebKey().setId(impl.getKid()) - .setKeyType(impl.getKty()) - .setKeyOps(impl.getKeyOps()) - .setN(impl.getN()) - .setE(impl.getE()) - .setD(impl.getD()) - .setDp(impl.getDp()) - .setDq(impl.getDq()) - .setQi(impl.getQi()) - .setP(impl.getP()) - .setQ(impl.getQ()) - .setK(impl.getK()) - .setT(impl.getT()) - .setCurveName(impl.getCrv()) - .setX(impl.getX()) - .setY(impl.getY()); - } - - public static com.azure.security.keyvault.keys.implementation.models.JsonWebKey mapJsonWebKey(JsonWebKey key) { - if (key == null) { - return null; - } - - return new com.azure.security.keyvault.keys.implementation.models.JsonWebKey().setKid(key.getId()) - .setKty(key.getKeyType()) - .setKeyOps(key.getKeyOps()) - .setN(key.getN()) - .setE(key.getE()) - .setD(key.getD()) - .setDp(key.getDp()) - .setDq(key.getDq()) - .setQi(key.getQi()) - .setP(key.getP()) - .setQ(key.getQ()) - .setK(key.getK()) - .setT(key.getT()) - .setCrv(key.getCurveName()) - .setX(key.getX()) - .setY(key.getY()); - } - - public static KeyAttributes createKeyAttributes(CreateKeyOptions options) { - if (options == null) { - return null; - } - - return new KeyAttributes().setEnabled(options.isEnabled()) - .setExportable(options.isExportable()) - .setExpires(options.getExpiresOn()) - .setNotBefore(options.getNotBefore()); - } - - public static KeyAttributes createKeyAttributes(KeyProperties properties) { - if (properties == null) { - return null; - } - - return new KeyAttributes().setEnabled(properties.isEnabled()) - .setExportable(properties.isExportable()) - .setExpires(properties.getExpiresOn()) - .setNotBefore(properties.getNotBefore()); - } - - private static void populateKeyProperties(KeyBundle bundle, KeyProperties properties) { - if (bundle == null) { - return; - } - - properties.setReleasePolicy(mapKeyReleasePolicyImpl(bundle.getReleasePolicy())).setTags(bundle.getTags()); - - KeyPropertiesHelper.setManaged(properties, bundle.isManaged()); - KeyPropertiesHelper.setId(properties, bundle.getKey().getKid()); - unpackId(bundle.getKey().getKid(), name -> KeyPropertiesHelper.setName(properties, name), - version -> KeyPropertiesHelper.setVersion(properties, version)); - - KeyAttributes attributes = bundle.getAttributes(); - if (attributes != null) { - properties.setEnabled(attributes.isEnabled()) - .setEnabled(attributes.isEnabled()) - .setExportable(attributes.isExportable()) - .setNotBefore(attributes.getNotBefore()) - .setExpiresOn(attributes.getExpires()); - - KeyPropertiesHelper.setCreatedOn(properties, attributes.getCreated()); - KeyPropertiesHelper.setUpdatedOn(properties, attributes.getUpdated()); - KeyPropertiesHelper.setRecoveryLevel(properties, Objects.toString(attributes.getRecoveryLevel(), null)); - KeyPropertiesHelper.setRecoverableDays(properties, attributes.getRecoverableDays()); - KeyPropertiesHelper.setHsmPlatform(properties, attributes.getHsmPlatform()); - } - } - - public static com.azure.security.keyvault.keys.implementation.models.KeyReleasePolicy - mapKeyReleasePolicy(KeyReleasePolicy policy) { - if (policy == null) { - return null; - } - - return new com.azure.security.keyvault.keys.implementation.models.KeyReleasePolicy() - .setContentType(policy.getContentType()) - .setImmutable(policy.isImmutable()) - .setEncodedPolicy(policy.getEncodedPolicy().toBytes()); - } - - private static KeyReleasePolicy - mapKeyReleasePolicyImpl(com.azure.security.keyvault.keys.implementation.models.KeyReleasePolicy impl) { - if (impl == null) { - return null; - } - - return new KeyReleasePolicy(BinaryData.fromBytes(impl.getEncodedPolicy())).setContentType(impl.getContentType()) - .setImmutable(impl.isImmutable()); - } - - public static KeyRotationPolicy - mapKeyRotationPolicyImpl(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy impl) { - return (impl == null) ? null : KeyRotationPolicyHelper.createPolicy(impl); - } - - public static com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy - mapKeyRotationPolicy(KeyRotationPolicy policy) { - if (policy == null) { - return null; - } - - return KeyRotationPolicyHelper.getImpl(policy); - } - - private static void unpackId(String keyId, Consumer nameConsumer, Consumer versionConsumer) { - if (CoreUtils.isNullOrEmpty(keyId)) { - return; - } - - try { - URL url = new URL(keyId); - String[] tokens = url.getPath().split("/"); - if (tokens.length >= 3) { - nameConsumer.accept(tokens[2]); - } - - if (tokens.length >= 4) { - versionConsumer.accept(tokens[3]); - } - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - - private KeyVaultKeysModelsUtils() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java deleted file mode 100644 index 6edf08bbffa4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The key verify parameters. - */ -@Fluent -public final class KeyVerifyParameters implements JsonSerializable { - /* - * The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - */ - private JsonWebKeySignatureAlgorithm algorithm; - - /* - * The digest used for signing. - */ - private Base64Url digest; - - /* - * The signature to be verified. - */ - private Base64Url signature; - - /** - * Creates an instance of KeyVerifyParameters class. - */ - public KeyVerifyParameters() { - } - - /** - * Get the algorithm property: The signing/verification algorithm. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * - * @return the algorithm value. - */ - public JsonWebKeySignatureAlgorithm getAlgorithm() { - return this.algorithm; - } - - /** - * Set the algorithm property: The signing/verification algorithm. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * - * @param algorithm the algorithm value to set. - * @return the KeyVerifyParameters object itself. - */ - public KeyVerifyParameters setAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Get the digest property: The digest used for signing. - * - * @return the digest value. - */ - public byte[] getDigest() { - if (this.digest == null) { - return null; - } - return this.digest.decodedBytes(); - } - - /** - * Set the digest property: The digest used for signing. - * - * @param digest the digest value to set. - * @return the KeyVerifyParameters object itself. - */ - public KeyVerifyParameters setDigest(byte[] digest) { - if (digest == null) { - this.digest = null; - } else { - this.digest = Base64Url.encode(CoreUtils.clone(digest)); - } - return this; - } - - /** - * Get the signature property: The signature to be verified. - * - * @return the signature value. - */ - public byte[] getSignature() { - if (this.signature == null) { - return null; - } - return this.signature.decodedBytes(); - } - - /** - * Set the signature property: The signature to be verified. - * - * @param signature the signature value to set. - * @return the KeyVerifyParameters object itself. - */ - public KeyVerifyParameters setSignature(byte[] signature) { - if (signature == null) { - this.signature = null; - } else { - this.signature = Base64Url.encode(CoreUtils.clone(signature)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("alg", this.algorithm == null ? null : this.algorithm.toString()); - jsonWriter.writeStringField("digest", Objects.toString(this.digest, null)); - jsonWriter.writeStringField("value", Objects.toString(this.signature, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVerifyParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVerifyParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeyVerifyParameters. - */ - public static KeyVerifyParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVerifyParameters deserializedKeyVerifyParameters = new KeyVerifyParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("alg".equals(fieldName)) { - deserializedKeyVerifyParameters.algorithm - = JsonWebKeySignatureAlgorithm.fromString(reader.getString()); - } else if ("digest".equals(fieldName)) { - deserializedKeyVerifyParameters.digest - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else if ("value".equals(fieldName)) { - deserializedKeyVerifyParameters.signature - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVerifyParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java deleted file mode 100644 index 578a9a1a2509..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key verify result. - */ -@Immutable -public final class KeyVerifyResult implements JsonSerializable { - /* - * True if the signature is verified, otherwise false. - */ - private Boolean value; - - /** - * Creates an instance of KeyVerifyResult class. - */ - public KeyVerifyResult() { - } - - /** - * Get the value property: True if the signature is verified, otherwise false. - * - * @return the value value. - */ - public Boolean isValue() { - return this.value; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVerifyResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVerifyResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyVerifyResult. - */ - public static KeyVerifyResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVerifyResult deserializedKeyVerifyResult = new KeyVerifyResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedKeyVerifyResult.value = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVerifyResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java deleted file mode 100644 index 6476fe65a397..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Action and its trigger that will be performed by Key Vault over the lifetime of a key. - */ -@Fluent -public final class LifetimeActions implements JsonSerializable { - /* - * The condition that will execute the action. - */ - private LifetimeActionsTrigger trigger; - - /* - * The action that will be executed. - */ - private LifetimeActionsType action; - - /** - * Creates an instance of LifetimeActions class. - */ - public LifetimeActions() { - } - - /** - * Get the trigger property: The condition that will execute the action. - * - * @return the trigger value. - */ - public LifetimeActionsTrigger getTrigger() { - return this.trigger; - } - - /** - * Set the trigger property: The condition that will execute the action. - * - * @param trigger the trigger value to set. - * @return the LifetimeActions object itself. - */ - public LifetimeActions setTrigger(LifetimeActionsTrigger trigger) { - this.trigger = trigger; - return this; - } - - /** - * Get the action property: The action that will be executed. - * - * @return the action value. - */ - public LifetimeActionsType getAction() { - return this.action; - } - - /** - * Set the action property: The action that will be executed. - * - * @param action the action value to set. - * @return the LifetimeActions object itself. - */ - public LifetimeActions setAction(LifetimeActionsType action) { - this.action = action; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("trigger", this.trigger); - jsonWriter.writeJsonField("action", this.action); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of LifetimeActions from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of LifetimeActions if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the LifetimeActions. - */ - public static LifetimeActions fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - LifetimeActions deserializedLifetimeActions = new LifetimeActions(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("trigger".equals(fieldName)) { - deserializedLifetimeActions.trigger = LifetimeActionsTrigger.fromJson(reader); - } else if ("action".equals(fieldName)) { - deserializedLifetimeActions.action = LifetimeActionsType.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedLifetimeActions; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java deleted file mode 100644 index e5c62cf2053a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * A condition to be satisfied for an action to be executed. - */ -@Fluent -public final class LifetimeActionsTrigger implements JsonSerializable { - /* - * Time after creation to attempt to rotate. It only applies to rotate. It will be in ISO 8601 duration format. - * Example: 90 days : "P90D" - */ - private String timeAfterCreate; - - /* - * Time before expiry to attempt to rotate or notify. It will be in ISO 8601 duration format. Example: 90 days : - * "P90D" - */ - private String timeBeforeExpiry; - - /** - * Creates an instance of LifetimeActionsTrigger class. - */ - public LifetimeActionsTrigger() { - } - - /** - * Get the timeAfterCreate property: Time after creation to attempt to rotate. It only applies to rotate. It will be - * in ISO 8601 duration format. Example: 90 days : "P90D". - * - * @return the timeAfterCreate value. - */ - public String getTimeAfterCreate() { - return this.timeAfterCreate; - } - - /** - * Set the timeAfterCreate property: Time after creation to attempt to rotate. It only applies to rotate. It will be - * in ISO 8601 duration format. Example: 90 days : "P90D". - * - * @param timeAfterCreate the timeAfterCreate value to set. - * @return the LifetimeActionsTrigger object itself. - */ - public LifetimeActionsTrigger setTimeAfterCreate(String timeAfterCreate) { - this.timeAfterCreate = timeAfterCreate; - return this; - } - - /** - * Get the timeBeforeExpiry property: Time before expiry to attempt to rotate or notify. It will be in ISO 8601 - * duration format. Example: 90 days : "P90D". - * - * @return the timeBeforeExpiry value. - */ - public String getTimeBeforeExpiry() { - return this.timeBeforeExpiry; - } - - /** - * Set the timeBeforeExpiry property: Time before expiry to attempt to rotate or notify. It will be in ISO 8601 - * duration format. Example: 90 days : "P90D". - * - * @param timeBeforeExpiry the timeBeforeExpiry value to set. - * @return the LifetimeActionsTrigger object itself. - */ - public LifetimeActionsTrigger setTimeBeforeExpiry(String timeBeforeExpiry) { - this.timeBeforeExpiry = timeBeforeExpiry; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("timeAfterCreate", this.timeAfterCreate); - jsonWriter.writeStringField("timeBeforeExpiry", this.timeBeforeExpiry); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of LifetimeActionsTrigger from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of LifetimeActionsTrigger if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IOException If an error occurs while reading the LifetimeActionsTrigger. - */ - public static LifetimeActionsTrigger fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - LifetimeActionsTrigger deserializedLifetimeActionsTrigger = new LifetimeActionsTrigger(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("timeAfterCreate".equals(fieldName)) { - deserializedLifetimeActionsTrigger.timeAfterCreate = reader.getString(); - } else if ("timeBeforeExpiry".equals(fieldName)) { - deserializedLifetimeActionsTrigger.timeBeforeExpiry = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedLifetimeActionsTrigger; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java deleted file mode 100644 index 931bf6d380c0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -import java.io.IOException; - -/** - * The action that will be executed. - */ -@Fluent -public final class LifetimeActionsType implements JsonSerializable { - /* - * The type of the action. The value should be compared case-insensitively. - */ - private KeyRotationPolicyAction type; - - /** - * Creates an instance of LifetimeActionsType class. - */ - public LifetimeActionsType() { - } - - /** - * Get the type property: The type of the action. The value should be compared case-insensitively. - * - * @return the type value. - */ - public KeyRotationPolicyAction getType() { - return this.type; - } - - /** - * Set the type property: The type of the action. The value should be compared case-insensitively. - * - * @param type the type value to set. - * @return the LifetimeActionsType object itself. - */ - public LifetimeActionsType setType(KeyRotationPolicyAction type) { - this.type = type; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of LifetimeActionsType from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of LifetimeActionsType if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the LifetimeActionsType. - */ - public static LifetimeActionsType fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - LifetimeActionsType deserializedLifetimeActionsType = new LifetimeActionsType(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("type".equals(fieldName)) { - deserializedLifetimeActionsType.type = KeyRotationPolicyAction.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedLifetimeActionsType; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java deleted file mode 100644 index 78672c3d9dd8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The get random bytes response object containing the bytes. - */ -@Fluent -public final class RandomBytes implements JsonSerializable { - /* - * The bytes encoded as a base64url string. - */ - private Base64Url value; - - /** - * Creates an instance of RandomBytes class. - */ - public RandomBytes() { - } - - /** - * Get the value property: The bytes encoded as a base64url string. - * - * @return the value value. - */ - public byte[] getValue() { - if (this.value == null) { - return null; - } - return this.value.decodedBytes(); - } - - /** - * Set the value property: The bytes encoded as a base64url string. - * - * @param value the value value to set. - * @return the RandomBytes object itself. - */ - public RandomBytes setValue(byte[] value) { - if (value == null) { - this.value = null; - } else { - this.value = Base64Url.encode(CoreUtils.clone(value)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", Objects.toString(this.value, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RandomBytes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RandomBytes if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the RandomBytes. - */ - public static RandomBytes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RandomBytes deserializedRandomBytes = new RandomBytes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedRandomBytes.value - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedRandomBytes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretKey.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretKey.java deleted file mode 100644 index 25fa889a216f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretKey.java +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; - -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Objects; - -/** - * Secret key - */ -public final class SecretKey implements JsonSerializable { - - /* - * The value of the secret. - */ - private String value; - - /* - * The secret properties. - */ - private SecretProperties properties; - - /** - * Creates an empty instance of the Secret. - */ - public SecretKey() { - properties = new SecretProperties(); - } - - /** - * Creates a Secret with {@code name} and {@code value}. - * - * @param name The name of the secret. - * @param value the value of the secret. - */ - public SecretKey(String name, String value) { - properties = new SecretProperties(name); - this.value = value; - } - - /** - * Get the value of the secret. - * - * @return the secret value - */ - public String getValue() { - return this.value; - } - - /** - * Get the secret identifier. - * - * @return the secret identifier. - */ - public String getId() { - return properties.getId(); - } - - /** - * Get the secret name. - * - * @return the secret name. - */ - public String getName() { - return properties.getName(); - } - - /** - * Get the secret properties - * @return the Secret properties - */ - public SecretProperties getProperties() { - return this.properties; - } - - /** - * Set the secret properties - * @param properties The Secret properties - * @throws NullPointerException if {@code properties} is null. - * @return the updated secret key object - */ - public SecretKey setProperties(SecretProperties properties) { - Objects.requireNonNull(properties); - properties.name = this.properties.name; - this.properties = properties; - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject().writeStringField("value", this.value); - - if (properties != null) { - jsonWriter.writeMapField("tags", properties.getTags(), JsonWriter::writeString) - .writeStringField("contentType", properties.getContentType()) - .writeStartObject("attributes") - .writeBooleanField("enabled", properties.isEnabled()); - if (properties.getNotBefore() != null) { - - jsonWriter.writeNumberField("nbf", properties.getNotBefore().toEpochSecond()); - } - if (properties.getExpiresOn() != null) { - jsonWriter.writeNumberField("exp", properties.getExpiresOn().toEpochSecond()); - } - jsonWriter.writeEndObject(); - } - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretKey from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretKey if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SecretKey. - */ - public static SecretKey fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretKey secretKey = new SecretKey(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - secretKey.value = reader.getString(); - } else if ("id".equals(fieldName)) { - secretKey.properties.id = reader.getString(); - KeyVaultKeysUtils.unpackId(secretKey.properties.id, name -> secretKey.properties.name = name, - version -> secretKey.properties.version = version); - } else if ("contentType".equals(fieldName)) { - secretKey.properties.contentType = reader.getString(); - } else if ("attributes".equals(fieldName)) { - while (reader.nextToken() != JsonToken.END_OBJECT) { - fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - secretKey.properties.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - secretKey.properties.notBefore = reader.getNullable(nonNull -> OffsetDateTime - .ofInstant(Instant.ofEpochSecond(nonNull.getLong()), ZoneOffset.UTC)); - } else if ("exp".equals(fieldName)) { - secretKey.properties.expiresOn = reader.getNullable(nonNull -> OffsetDateTime - .ofInstant(Instant.ofEpochSecond(nonNull.getLong()), ZoneOffset.UTC)); - } else if ("created".equals(fieldName)) { - secretKey.properties.createdOn = reader.getNullable(nonNull -> OffsetDateTime - .ofInstant(Instant.ofEpochSecond(nonNull.getLong()), ZoneOffset.UTC)); - } else if ("updated".equals(fieldName)) { - secretKey.properties.updatedOn = reader.getNullable(nonNull -> OffsetDateTime - .ofInstant(Instant.ofEpochSecond(nonNull.getLong()), ZoneOffset.UTC)); - } else if ("recoverableDays".equals(fieldName)) { - secretKey.properties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("recoveryLevel".equals(fieldName)) { - secretKey.properties.recoveryLevel = reader.getString(); - } else { - reader.skipChildren(); - } - } - } else if ("tags".equals(fieldName)) { - secretKey.properties.tags = reader.readMap(JsonReader::getString); - } else if ("kid".equals(fieldName)) { - secretKey.properties.keyId = reader.getString(); - } else if ("managed".equals(fieldName)) { - secretKey.properties.managed = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return secretKey; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretProperties.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretProperties.java deleted file mode 100644 index 7030ef72fe25..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretProperties.java +++ /dev/null @@ -1,380 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; - -import java.io.IOException; -import java.time.OffsetDateTime; -import java.util.Map; -import java.util.Objects; - -/** - * Secret properties. - */ -public final class SecretProperties implements JsonSerializable { - /* - * The secret id. - */ - String id; - - /* - * The secret version. - */ - String version; - - /* - * Determines whether the object is enabled. - */ - Boolean enabled; - - /* - * Not before date in UTC. - */ - OffsetDateTime notBefore; - - /* - * Expiry date in UTC. - */ - OffsetDateTime expiresOn; - - /* - * Creation time in UTC. - */ - OffsetDateTime createdOn; - - /* - * Last updated time in UTC. - */ - OffsetDateTime updatedOn; - - /* - * The secret name. - */ - String name; - - /* - * Reflects the deletion recovery level currently in effect for secrets in - * the current vault. If it contains 'Purgeable', the secret can be - * permanently deleted by a privileged user; otherwise, only the system can - * purge the secret, at the end of the retention interval. Possible values - * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', - * 'Recoverable+ProtectedSubscription'. - */ - String recoveryLevel; - - /* - * The content type of the secret. - */ - String contentType; - - /* - * Application specific metadata in the form of key-value pairs. - */ - Map tags; - - /* - * If this is a secret backing a KV certificate, then this field specifies - * the corresponding key backing the KV certificate. - */ - String keyId; - - /* - * True if the secret's lifetime is managed by key vault. If this is a - * secret backing a certificate, then managed will be true. - */ - Boolean managed; - - SecretProperties(String secretName) { - this.name = secretName; - } - - /** - * Creates empty instance of SecretProperties. - */ - public SecretProperties() { - } - - /** - * Get the secret name. - * - * @return the name of the secret. - */ - public String getName() { - return this.name; - } - - /** - * Get the recovery level of the secret. - - * @return the recoveryLevel of the secret. - */ - public String getRecoveryLevel() { - return recoveryLevel; - } - - /** - * Get the enabled value. - * - * @return the enabled value - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * The number of days a secret is retained before being deleted for a soft delete-enabled Key Vault. - */ - Integer recoverableDays; - - /** - * Set the enabled value. - * - * @param enabled The enabled value to set - * @throws NullPointerException if {@code enabled} is null. - * @return the SecretProperties object itself. - */ - public SecretProperties setEnabled(Boolean enabled) { - Objects.requireNonNull(enabled); - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore UTC time. - * - * @return the notBefore UTC time. - */ - public OffsetDateTime getNotBefore() { - return notBefore; - } - - /** - * Gets the number of days a secret is retained before being deleted for a soft delete-enabled Key Vault. - * @return the recoverable days. - */ - public Integer getRecoverableDays() { - return recoverableDays; - } - - /** - * Set the {@link OffsetDateTime notBefore} UTC time. - * - * @param notBefore The notBefore UTC time to set - * @return the SecretProperties object itself. - */ - public SecretProperties setNotBefore(OffsetDateTime notBefore) { - this.notBefore = notBefore; - return this; - } - - /** - * Get the Secret Expiry time in UTC. - * - * @return the expires UTC time. - */ - public OffsetDateTime getExpiresOn() { - if (this.expiresOn == null) { - return null; - } - return this.expiresOn; - } - - /** - * Set the {@link OffsetDateTime expires} UTC time. - * - * @param expiresOn The expiry time to set for the secret. - * @return the SecretProperties object itself. - */ - public SecretProperties setExpiresOn(OffsetDateTime expiresOn) { - this.expiresOn = expiresOn; - return this; - } - - /** - * Get the UTC time at which secret was created. - * - * @return the created UTC time. - */ - public OffsetDateTime getCreatedOn() { - return createdOn; - } - - /** - * Get the UTC time at which secret was last updated. - * - * @return the last updated UTC time. - */ - public OffsetDateTime getUpdatedOn() { - return updatedOn; - } - - /** - * Get the secret identifier. - * - * @return the secret identifier. - */ - public String getId() { - return this.id; - } - - /** - * Get the content type. - * - * @return the content type. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType. - * - * @param contentType The contentType to set - * @return the updated SecretProperties object itself. - */ - public SecretProperties setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Get the tags associated with the secret. - * - * @return the value of the tags. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags to be associated with the secret. - * - * @param tags The tags to set - * @return the updated SecretProperties object itself. - */ - public SecretProperties setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the keyId identifier. - * - * @return the keyId identifier. - */ - public String getKeyId() { - return this.keyId; - } - - /** - * Get the managed value. - * - * @return the managed value - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Get the version of the secret. - * - * @return the version of the secret. - */ - public String getVersion() { - return this.version; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("contentType", contentType) - .writeMapField("tags", tags, JsonWriter::writeString) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link SecretProperties}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link SecretProperties} that the JSON stream represented, may return null. - * @throws IOException If a {@link SecretProperties} fails to be read from the {@code jsonReader}. - */ - public static SecretProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretProperties secretProperties = new SecretProperties(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("contentType".equals(fieldName)) { - secretProperties.contentType = reader.getString(); - } else if ("tags".equals(fieldName)) { - secretProperties.tags = reader.readMap(JsonReader::getString); - } else if ("kid".equals(fieldName)) { - secretProperties.keyId = reader.getString(); - } else if ("managed".equals(fieldName)) { - secretProperties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("recoverableDays".equals(fieldName)) { - secretProperties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - deserializeAttributes(reader, secretProperties); - } else if ("id".equals(fieldName)) { - secretProperties.id = reader.getString(); - KeyVaultKeysUtils.unpackId(secretProperties.id, name -> secretProperties.name = name, - version -> secretProperties.version = version); - } else { - reader.skipChildren(); - } - } - - return secretProperties; - }); - } - - static void deserializeAttributes(JsonReader reader, SecretProperties secretProperties) throws IOException { - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - secretProperties.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - secretProperties.notBefore = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("exp".equals(fieldName)) { - secretProperties.expiresOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("created".equals(fieldName)) { - secretProperties.createdOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("updated".equals(fieldName)) { - secretProperties.updatedOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("recoveryLevel".equals(fieldName)) { - secretProperties.recoveryLevel = reader.getString(); - } else if ("contentType".equals(fieldName)) { - String contentType = reader.getString(); - secretProperties.contentType = contentType == null ? secretProperties.contentType : contentType; - } else if ("keyId".equals(fieldName)) { - String keyId = reader.getString(); - secretProperties.keyId = keyId == null ? secretProperties.keyId : keyId; - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(JsonReader::getString); - secretProperties.tags = tags == null ? secretProperties.tags : tags; - } else if ("managed".equals(fieldName)) { - Boolean managed = reader.getNullable(JsonReader::getBoolean); - secretProperties.managed = managed == null ? secretProperties.managed : managed; - } else if ("recoverableDays".equals(fieldName)) { - secretProperties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("id".equals(fieldName)) { - secretProperties.id = reader.getString(); - KeyVaultKeysUtils.unpackId(secretProperties.id, name -> secretProperties.name = name, - version -> secretProperties.version = version); - } else { - reader.skipChildren(); - } - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestAttributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestAttributes.java deleted file mode 100644 index b009a152a13b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestAttributes.java +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The object attributes managed by the Cryptography service. - */ -@Fluent -public final class SecretRequestAttributes implements JsonSerializable { - - /** - * Creates an instance of SecretRequestAttributes. Reads secretProperties.notBefore, secretProperties.expires and - * secretProperties.enabled fields from {@code secretProperties} - * @param secretProperties the {@link SecretProperties} object with populated attributes - */ - public SecretRequestAttributes(SecretProperties secretProperties) { - if (secretProperties.getNotBefore() != null) { - this.notBefore = secretProperties.getNotBefore().toEpochSecond(); - } - if (secretProperties.getExpiresOn() != null) { - this.expires = secretProperties.getExpiresOn().toEpochSecond(); - } - this.enabled = secretProperties.isEnabled(); - } - - private SecretRequestAttributes() { - } - - /* - * The secret value. - */ - private String value; - - /* - * The secret id. - */ - private String id; - - /* - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Not before date in UTC. - */ - private Long notBefore; - - /* - * Expiry date in UTC. - */ - private Long expires; - - /* - * Creation time in UTC. - */ - private Long created; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /** - * Get the enabled value. - * - * @return the enabled value - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled value. - * - * @param enabled the enabled value to set - * @return the Attributes object itself. - */ - public SecretRequestAttributes getEnabled(Boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore value. - * - * @return the notBefore value - */ - public OffsetDateTime getNotBefore() { - if (this.notBefore == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(this.notBefore * 1000L), ZoneOffset.UTC); - } - - /** - * Set the notBefore value. - * - * @param notBefore the notBefore value to set - * @return the Attributes object itself. - */ - public SecretRequestAttributes setNotBefore(OffsetDateTime notBefore) { - if (notBefore == null) { - this.notBefore = null; - } else { - this.notBefore = OffsetDateTime.ofInstant(notBefore.toInstant(), ZoneOffset.UTC).toEpochSecond(); - } - return this; - } - - /** - * Get the expires value. - * - * @return the expires value - */ - public OffsetDateTime getExpires() { - if (this.expires == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(this.expires * 1000L), ZoneOffset.UTC); - } - - /** - * Set the expires value. - * - * @param expires the expires value to set - * @return the Attributes object itself. - */ - public SecretRequestAttributes setExpires(OffsetDateTime expires) { - if (expires == null) { - this.expires = null; - } else { - this.expires = OffsetDateTime.ofInstant(expires.toInstant(), ZoneOffset.UTC).toEpochSecond(); - } - return this; - } - - /** - * Get the created value. - * - * @return the created value - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(this.created * 1000L), ZoneOffset.UTC); - } - - /** - * Get the updated value. - * - * @return the updated value - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(this.updated * 1000L), ZoneOffset.UTC); - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("value", value) - .writeStringField("id", id) - .writeBooleanField("enabled", enabled) - .writeNumberField("nbf", notBefore) - .writeNumberField("exp", expires) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link SecretRequestAttributes}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link SecretRequestAttributes} that the JSON stream represented, may return null. - * @throws IOException If a {@link SecretRequestAttributes} fails to be read from the {@code jsonReader}. - */ - public static SecretRequestAttributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretRequestAttributes attributes = new SecretRequestAttributes(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - attributes.value = reader.getString(); - } else if ("id".equals(fieldName)) { - attributes.id = reader.getString(); - } else if ("enabled".equals(fieldName)) { - attributes.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - attributes.notBefore = reader.getNullable(JsonReader::getLong); - } else if ("exp".equals(fieldName)) { - attributes.expires = reader.getNullable(JsonReader::getLong); - } else if ("created".equals(fieldName)) { - attributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - attributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return attributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestParameters.java deleted file mode 100644 index ad97ea6a2095..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/SecretRequestParameters.java +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.util.Map; - -/** - * Represents a set of request options used in REST requests intitiated by Cryptography service. - */ -@Fluent -public final class SecretRequestParameters implements JsonSerializable { - /* - * The value of the secret. - */ - private String value; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * Type of the secret value such as a password. - */ - private String contentType; - - /* - * The secret management attributes. - */ - private SecretRequestAttributes secretRequestAttributes; - - /** - * Get the value value. - * - * @return the value value - */ - public String getValue() { - return this.value; - } - - /** - * Set the value value. - * - * @param value the value value to set - * @return the SecretRequestParameters object itself. - */ - public SecretRequestParameters setValue(String value) { - this.value = value; - return this; - } - - /** - * Get the tags value. - * - * @return the tags value - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags value. - * - * @param tags the tags value to set - * @return the SecretRequestParameters object itself. - */ - public SecretRequestParameters setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the contentType value. - * - * @return the contentType value - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType value. - * - * @param contentType the contentType value to set - * @return the SecretRequestParameters object itself. - */ - public SecretRequestParameters setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Get the secretRequestAttributes value. - * - * @return the SecretRequestAttributes value - */ - public SecretRequestAttributes getSecretAttributes() { - return this.secretRequestAttributes; - } - - /** - * Set the secretRequestAttributes value. - * - * @param secretRequestAttributes the secretRequestAttributes to set - * @return the SecretRequestParameters object itself. - */ - public SecretRequestParameters setSecretAttributes(SecretRequestAttributes secretRequestAttributes) { - this.secretRequestAttributes = secretRequestAttributes; - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("value", value) - .writeMapField("tags", tags, JsonWriter::writeString) - .writeStringField("contentType", contentType) - .writeJsonField("attributes", secretRequestAttributes) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link SecretRequestParameters}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link SecretRequestParameters} that the JSON stream represented, may return null. - * @throws IOException If a {@link SecretRequestParameters} fails to be read from the {@code jsonReader}. - */ - public static SecretRequestParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretRequestParameters attributes = new SecretRequestParameters(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - attributes.value = reader.getString(); - } else if ("tags".equals(fieldName)) { - attributes.tags = reader.readMap(JsonReader::getString); - } else if ("contentType".equals(fieldName)) { - attributes.contentType = reader.getString(); - } else if ("attributes".equals(fieldName)) { - attributes.secretRequestAttributes = SecretRequestAttributes.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return attributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java deleted file mode 100644 index ea5b08c3e06c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the data models for KeyClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. - */ -package com.azure.security.keyvault.keys.implementation.models; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java deleted file mode 100644 index d1c0e17672db..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the implementations for KeyClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. - */ -package com.azure.security.keyvault.keys.implementation; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateEcKeyOptions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateEcKeyOptions.java deleted file mode 100644 index c60845ed0625..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateEcKeyOptions.java +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; - -import java.time.OffsetDateTime; -import java.util.Map; - -/** - * Represents the configurable options to create an EC key. - */ -@Fluent -public class CreateEcKeyOptions extends CreateKeyOptions { - /** - * The EC key curve. - */ - private KeyCurveName curveName; - - /** - * The hardware protected indicator for the key. - */ - private boolean hardwareProtected; - - /** - * Creates a {@link CreateEcKeyOptions} with {@code name} as name of the EC key. - * - * @param name The name of the EC key. - */ - public CreateEcKeyOptions(String name) { - super(name, KeyType.EC); - } - - /** - * Get the curve. - * - * @return The curve name. - */ - public KeyCurveName getCurveName() { - return this.curveName; - } - - /** - * Set the curve name. - * - * @param curveName The curve name to set. - * - * @return The {@link CreateEcKeyOptions} object. - */ - public CreateEcKeyOptions setCurveName(KeyCurveName curveName) { - this.curveName = curveName; - - return this; - } - - /** - * Get the HSM value of the key being created. - * - * @return The HSM value. - */ - public Boolean isHardwareProtected() { - return this.hardwareProtected; - } - - /** - * Set whether the key being created is of HSM type or not. - * - * @param hardwareProtected The HSM value to set. - * - * @return The {@link CreateEcKeyOptions} object. - */ - public CreateEcKeyOptions setHardwareProtected(Boolean hardwareProtected) { - this.hardwareProtected = hardwareProtected; - KeyType keyType = hardwareProtected ? KeyType.EC_HSM : KeyType.EC; - - setKeyType(keyType); - - return this; - } - - /** - * Set the key operations. - * - * @param keyOperations The key operations to set. - * - * @return The {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setKeyOperations(KeyOperation... keyOperations) { - super.setKeyOperations(keyOperations); - return this; - } - - /** - * Set the {@link OffsetDateTime notBefore} UTC time. - * - * @param notBefore The notBefore UTC time to set. - * - * @return The {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - - return this; - } - - /** - * Set the {@link OffsetDateTime expires} UTC time. - * - * @param expiresOn The expiry time to set for the key. - * - * @return The {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setExpiresOn(OffsetDateTime expiresOn) { - super.setExpiresOn(expiresOn); - - return this; - } - - /** - * Set the tags to be associated with the key. - * - * @param tags The tags to set. - * - * @return The {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setTags(Map tags) { - super.setTags(tags); - - return this; - } - - /** - * Set a value that indicates if the key is enabled. - * - * @param enabled The enabled value to set. - * - * @return The {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setEnabled(Boolean enabled) { - super.setEnabled(enabled); - - return this; - } - - /** - * Set a flag that indicates if the private key can be exported. - * - * @param exportable A flag that indicates if the private key can be exported. - * - * @return The updated {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setExportable(Boolean exportable) { - super.setExportable(exportable); - - return this; - } - - /** - * Set the policy rules under which the key can be exported. - * - * @param releasePolicy The policy rules to set. - * - * @return The updated {@link CreateEcKeyOptions} object. - */ - @Override - public CreateEcKeyOptions setReleasePolicy(KeyReleasePolicy releasePolicy) { - super.setReleasePolicy(releasePolicy); - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateKeyOptions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateKeyOptions.java deleted file mode 100644 index fb32722775d4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateKeyOptions.java +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; - -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Represents the configurable options to create a key. - */ -@Fluent -public class CreateKeyOptions { - /** - * The key name. - */ - private final String name; - - /** - * The type of the key. - */ - private KeyType keyType; - - /** - * The key operations. - */ - private List keyOperations; - - /** - * Not before date in UTC. - */ - private OffsetDateTime notBefore; - - /** - * Expiry date in UTC. - */ - private OffsetDateTime expiresOn; - - /** - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /** - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Indicates if the private key can be exported. - */ - private Boolean exportable; - - /* - * The policy rules under which the key can be exported. - */ - private KeyReleasePolicy releasePolicy; - - /** - * Creates instance of {@link CreateKeyOptions} with {@code name} as key name and {@code keyType} as type of the - * key. - * - * @param name The name of the key to create. - * @param keyType The type of the key to create. - */ - public CreateKeyOptions(String name, KeyType keyType) { - this.name = name; - this.keyType = keyType; - } - - /** - * Get the key name. - * - * @return The name of the key. - */ - public String getName() { - return this.name; - } - - /** - * Get the key type. - * - * @return The key type. - */ - public KeyType getKeyType() { - return this.keyType; - } - - void setKeyType(KeyType keyType) { - this.keyType = keyType; - } - - /** - * Get the key operations. - * - * @return The key operations. - */ - public List getKeyOperations() { - return this.keyOperations; - } - - /** - * Set the key operations. - * - * @param keyOperations The key operations to set. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setKeyOperations(KeyOperation... keyOperations) { - this.keyOperations = Arrays.asList(keyOperations); - - return this; - } - - /** - * Get the {@link OffsetDateTime key's notBefore time} in UTC. - * - * @return The {@link OffsetDateTime key's notBefore time} in UTC. - */ - public OffsetDateTime getNotBefore() { - return notBefore; - } - - /** - * Set the {@link OffsetDateTime key's notBefore time} in UTC. - * - * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setNotBefore(OffsetDateTime notBefore) { - this.notBefore = notBefore; - - return this; - } - - /** - * Get the {@link OffsetDateTime key expiration time} in UTC. - * - * @return The {@link OffsetDateTime key expiration time} in UTC. - */ - public OffsetDateTime getExpiresOn() { - return this.expiresOn; - } - - /** - * Set the {@link OffsetDateTime key expiration time} in UTC. - * - * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setExpiresOn(OffsetDateTime expiresOn) { - this.expiresOn = expiresOn; - - return this; - } - - /** - * Get the tags associated with the key. - * - * @return The tag names and values. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags to be associated with the key. - * - * @param tags The tags to set. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setTags(Map tags) { - this.tags = tags; - - return this; - } - - /** - * Get the enabled value. - * - * @return The enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set a value that indicates if the key is enabled. - * - * @param enabled The enabled value to set. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setEnabled(Boolean enabled) { - this.enabled = enabled; - - return this; - } - - /** - * Get a flag that indicates if the private key can be exported. - * - * @return A flag that indicates if the private key can be exported. - */ - public Boolean isExportable() { - return this.exportable; - } - - /** - * Set a flag that indicates if the private key can be exported. - * - * @param exportable A flag that indicates if the private key can be exported. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setExportable(Boolean exportable) { - this.exportable = exportable; - - return this; - } - - /** - * Get the policy rules under which the key can be exported. - * - * @return The policy rules under which the key can be exported. - */ - public KeyReleasePolicy getReleasePolicy() { - return this.releasePolicy; - } - - /** - * Set the policy rules under which the key can be exported. - * - * @param releasePolicy The policy rules to set. - * - * @return The updated {@link CreateKeyOptions} object. - */ - public CreateKeyOptions setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateOctKeyOptions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateOctKeyOptions.java deleted file mode 100644 index ca73c9196e1b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateOctKeyOptions.java +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; - -import java.time.OffsetDateTime; -import java.util.Map; - -/** - * Represents the configurable options to create a symmetric key. - */ -@Fluent -public class CreateOctKeyOptions extends CreateKeyOptions { - /** - * The key size. - */ - private Integer keySize; - - /** - * The hardware protected indicator for the key. - */ - private boolean hardwareProtected; - - /** - * Creates a {@link CreateOctKeyOptions} with {@code name} as name of the key. - * - * @param name The name of the key. - */ - public CreateOctKeyOptions(String name) { - super(name, KeyType.OCT); - } - - /** - * Sets the key size in bits, such as 128, 192, or 256. If {@code null}, the service default is used. - * - * @param keySize The key size in bits to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - public CreateOctKeyOptions setKeySize(Integer keySize) { - this.keySize = keySize; - - return this; - } - - /** - * Gets the key size in bits, such as 128, 192, or 256. - * - * @return The key size in bits. - */ - public Integer getKeySize() { - return this.keySize; - } - - /** - * Set whether the key being created is of HSM type or not. - * - * @param hardwareProtected The HSM value to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - public CreateOctKeyOptions setHardwareProtected(Boolean hardwareProtected) { - this.hardwareProtected = hardwareProtected; - KeyType keyType = hardwareProtected ? KeyType.OCT_HSM : KeyType.OCT; - - setKeyType(keyType); - - return this; - } - - /** - * Get the HSM value of the key being created. - * - * @return the HSM value. - */ - public Boolean isHardwareProtected() { - return this.hardwareProtected; - } - - /** - * Set the key operations. - * - * @param keyOperations The key operations to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setKeyOperations(KeyOperation... keyOperations) { - super.setKeyOperations(keyOperations); - - return this; - } - - /** - * Set the {@link OffsetDateTime notBefore} UTC time. - * - * @param notBefore The notBefore UTC time to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - - return this; - } - - /** - * Set the {@link OffsetDateTime expires} UTC time. - * - * @param expiresOn The expiry time to set. for the key. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setExpiresOn(OffsetDateTime expiresOn) { - super.setExpiresOn(expiresOn); - - return this; - } - - /** - * Set the tags to be associated with the key. - * - * @param tags The tags to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setTags(Map tags) { - super.setTags(tags); - - return this; - } - - /** - * Set a value that indicates if the key is enabled. - * - * @param enabled The enabled value to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setEnabled(Boolean enabled) { - super.setEnabled(enabled); - - return this; - } - - /** - * Set a flag that indicates if the private key can be exported. - * - * @param exportable A flag that indicates if the private key can be exported. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setExportable(Boolean exportable) { - super.setExportable(exportable); - - return this; - } - - /** - * Set the policy rules under which the key can be exported. - * - * @param releasePolicy The policy rules to set. - * - * @return The updated {@link CreateOctKeyOptions} object. - */ - @Override - public CreateOctKeyOptions setReleasePolicy(KeyReleasePolicy releasePolicy) { - super.setReleasePolicy(releasePolicy); - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateRsaKeyOptions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateRsaKeyOptions.java deleted file mode 100644 index 0e7d1a3fbe5c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/CreateRsaKeyOptions.java +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; - -import java.time.OffsetDateTime; -import java.util.Map; - -/** - * Represents the configurable options to create an RSA key. - */ -@Fluent -public class CreateRsaKeyOptions extends CreateKeyOptions { - /** - * The RSA key size. - */ - private Integer keySize; - - /** - * The hardware protected indicator for the key. - */ - private boolean hardwareProtected; - - /** - * The public exponent for the key. - */ - private int publicExponent; - - /** - * Creates a {@link CreateRsaKeyOptions} with {@code name} as name of the RSA key. - * - * @param name The name of the key. - */ - public CreateRsaKeyOptions(String name) { - super(name, KeyType.RSA); - } - - /** - * Get the key size in bits. - * - * @return The key size in bits. - */ - public Integer getKeySize() { - return this.keySize; - } - - /** - * Set the key size in bits. - * - * @param keySize The key size in bits to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - public CreateRsaKeyOptions setKeySize(Integer keySize) { - this.keySize = keySize; - - return this; - } - - /** - * Get the HSM value of the key being created. - * - * @return The HSM value. - */ - public Boolean isHardwareProtected() { - return this.hardwareProtected; - } - - /** - * Set whether the key being created is of HSM type or not. - * - * @param hardwareProtected The HSM value to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - public CreateRsaKeyOptions setHardwareProtected(Boolean hardwareProtected) { - this.hardwareProtected = hardwareProtected; - KeyType keyType = hardwareProtected ? KeyType.RSA_HSM : KeyType.RSA; - - setKeyType(keyType); - - return this; - } - - /** - * Get the public exponent for the key. - * - * @return The public exponent. - */ - public Integer getPublicExponent() { - return publicExponent; - } - - /** - * Set the public exponent for the key. - * - * @param publicExponent The public exponent to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - public CreateRsaKeyOptions setPublicExponent(Integer publicExponent) { - this.publicExponent = publicExponent; - - return this; - } - - /** - * Set the key operations. - * - * @param keyOperations The key operations to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setKeyOperations(KeyOperation... keyOperations) { - super.setKeyOperations(keyOperations); - - return this; - } - - /** - * Set the {@link OffsetDateTime notBefore} UTC time. - * - * @param notBefore The notBefore UTC time to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - - return this; - } - - /** - * Set the {@link OffsetDateTime expires} UTC time. - * - * @param expiresOn The expiry time to set for the key. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setExpiresOn(OffsetDateTime expiresOn) { - super.setExpiresOn(expiresOn); - - return this; - } - - /** - * Set the tags to be associated with the key. - * - * @param tags The tags to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setTags(Map tags) { - super.setTags(tags); - - return this; - } - - /** - * Set a value that indicates if the key is enabled. - * - * @param enabled The enabled value to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setEnabled(Boolean enabled) { - super.setEnabled(enabled); - - return this; - } - - /** - * Set a flag that indicates if the private key can be exported. - * - * @param exportable A flag that indicates if the private key can be exported. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setExportable(Boolean exportable) { - super.setExportable(exportable); - - return this; - } - - /** - * Set the policy rules under which the key can be exported. - * - * @param releasePolicy The policy rules to set. - * - * @return The updated {@link CreateRsaKeyOptions} object. - */ - @Override - public CreateRsaKeyOptions setReleasePolicy(KeyReleasePolicy releasePolicy) { - super.setReleasePolicy(releasePolicy); - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/DeletedKey.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/DeletedKey.java deleted file mode 100644 index bcf471c3d22a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/DeletedKey.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.KeyAsyncClient; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.implementation.DeletedKeyHelper; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; - -import java.io.IOException; -import java.time.OffsetDateTime; - -/** - * Deleted Key is the resource consisting of name, recovery id, deleted date, scheduled purge date and its attributes - * inherited from {@link KeyVaultKey}. - * It is managed by Key Service. - * - * @see KeyClient - * @see KeyAsyncClient - */ -public final class DeletedKey extends KeyVaultKey { - static { - DeletedKeyHelper.setAccessor(new DeletedKeyHelper.DeletedKeyAccessor() { - @Override - public DeletedKey createDeletedKey(JsonWebKey jsonWebKey) { - return new DeletedKey(jsonWebKey); - } - - @Override - public void setRecoveryId(DeletedKey deletedKey, String recoveryId) { - deletedKey.recoveryId = recoveryId; - } - - @Override - public void setScheduledPurgeDate(DeletedKey deletedKey, OffsetDateTime scheduledPurgeDate) { - deletedKey.scheduledPurgeDate = scheduledPurgeDate; - } - - @Override - public void setDeletedOn(DeletedKey deletedKey, OffsetDateTime deletedOn) { - deletedKey.deletedOn = deletedOn; - } - }); - } - - /** - * The url of the recovery object, used to identify and recover the deleted - * key. - */ - private String recoveryId; - - /** - * The time when the key is scheduled to be purged, in UTC. - */ - private OffsetDateTime scheduledPurgeDate; - - /** - * The time when the key was deleted, in UTC. - */ - private OffsetDateTime deletedOn; - - /** - * Creates a new instance of {@link DeletedKey}. - */ - public DeletedKey() { - } - - private DeletedKey(JsonWebKey jsonWebKey) { - super(jsonWebKey); - } - - private DeletedKey(JsonWebKey jsonWebKey, KeyProperties properties, String recoveryId, - OffsetDateTime scheduledPurgeDate, OffsetDateTime deletedOn) { - super(jsonWebKey, properties); - - this.recoveryId = recoveryId; - this.scheduledPurgeDate = scheduledPurgeDate; - this.deletedOn = deletedOn; - } - - /** - * Get the recoveryId identifier. - * - * @return the recoveryId identifier. - */ - public String getRecoveryId() { - return this.recoveryId; - } - - /** - * Get the scheduled purge UTC time. - * - * @return the scheduledPurgeDate UTC time. - */ - public OffsetDateTime getScheduledPurgeDate() { - return scheduledPurgeDate; - } - - /** - * Get the deleted UTC time. - * - * @return the deletedDate UTC time. - */ - public OffsetDateTime getDeletedOn() { - return this.deletedOn; - } - - /** - * Get the key value. - * - * @return the key value - */ - public JsonWebKey getKey() { - return super.getKey(); - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeJsonField("key", getKey()) - .writeStringField("recoveryId", recoveryId) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link DeletedKey}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link DeletedKey} that the JSON stream represented, may return null. - * @throws IOException If a {@link DeletedKey} fails to be read from the {@code jsonReader}. - */ - public static DeletedKey fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - JsonWebKey webKey = null; - KeyProperties properties = new KeyProperties(); - String recoveryId = null; - OffsetDateTime scheduledPurgeDate = null; - OffsetDateTime deletedOn = null; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("key".equals(fieldName)) { - webKey = JsonWebKey.fromJson(reader); - KeyVaultKeysUtils.unpackId(webKey.getId(), name -> properties.name = name, - version -> properties.version = version); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - while (reader.nextToken() != JsonToken.END_OBJECT) { - fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - properties.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("exportable".equals(fieldName)) { - properties.exportable = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - properties.notBefore = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("exp".equals(fieldName)) { - properties.expiresOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("created".equals(fieldName)) { - properties.createdOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("updated".equals(fieldName)) { - properties.updatedOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("recoveryLevel".equals(fieldName)) { - properties.recoveryLevel = reader.getString(); - } else if ("recoverableDays".equals(fieldName)) { - properties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - } else if ("tags".equals(fieldName)) { - properties.setTags(reader.readMap(JsonReader::getString)); - } else if ("managed".equals(fieldName)) { - properties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("release_policy".equals(fieldName)) { - properties.setReleasePolicy(KeyReleasePolicy.fromJson(reader)); - } else if ("recoveryId".equals(fieldName)) { - recoveryId = reader.getString(); - } else if ("scheduledPurgeDate".equals(fieldName)) { - scheduledPurgeDate = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("deletedDate".equals(fieldName)) { - deletedOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else { - reader.skipChildren(); - } - } - - return new DeletedKey(webKey, properties, recoveryId, scheduledPurgeDate, deletedOn); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ImportKeyOptions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ImportKeyOptions.java deleted file mode 100644 index 94664f1b7ac0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ImportKeyOptions.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; - -import java.time.OffsetDateTime; - -/** - * Represents the configurable options to import a key. - */ -@Fluent -public class ImportKeyOptions extends KeyProperties { - /** - * The JSON Web Key to import. - */ - private final JsonWebKey key; - - /** - * The hardware protected indicator for the key. - */ - private Boolean hardwareProtected; - - /** - * Creates instance of {@link ImportKeyOptions}. - * - * @param name The name of the key. - * @param key The key material to import. - */ - public ImportKeyOptions(String name, JsonWebKey key) { - super.name = name; - this.key = key; - } - - /** - * Set whether the key being imported is of HSM type or not. - * - * @param hardwareProtected The HSM value to set. - * - * @return The {@link ImportKeyOptions} object itself. - */ - public ImportKeyOptions setHardwareProtected(Boolean hardwareProtected) { - this.hardwareProtected = hardwareProtected; - - return this; - } - - /** - * Get the HSM value of the key being imported. - * - * @return The HSM value. - */ - public Boolean isHardwareProtected() { - return this.hardwareProtected; - } - - /** - * Set a value that indicates if the key is enabled. - * - * @param enabled The enabled value to set. - * - * @return The updated {@link ImportKeyOptions} object. - */ - @Override - public ImportKeyOptions setEnabled(Boolean enabled) { - this.enabled = enabled; - - return this; - } - - /** - * Get the key material of the key being imported. - * - * @return The key material. - */ - public JsonWebKey getKey() { - return key; - } - - /** - * Set the {@link OffsetDateTime key expiration time} in UTC. - * - * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. - * - * @return The updated {@link ImportKeyOptions} object. - */ - @Override - public ImportKeyOptions setExpiresOn(OffsetDateTime expiresOn) { - this.expiresOn = expiresOn; - - return this; - } - - /** - * Set the {@link OffsetDateTime key's notBefore time} in UTC. - * - * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. - * - * @return The updated {@link ImportKeyOptions} object. - */ - @Override - public ImportKeyOptions setNotBefore(OffsetDateTime notBefore) { - this.notBefore = notBefore; - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/JsonWebKey.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/JsonWebKey.java deleted file mode 100644 index a9aa43c243aa..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/JsonWebKey.java +++ /dev/null @@ -1,1209 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.ECGenParameterSpec; -import java.security.spec.ECParameterSpec; -import java.security.spec.ECPoint; -import java.security.spec.ECPrivateKeySpec; -import java.security.spec.ECPublicKeySpec; -import java.security.spec.EllipticCurve; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPrivateKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -/** - * As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18. - */ -public class JsonWebKey implements JsonSerializable { - private static final ClientLogger LOGGER = new ClientLogger(JsonWebKey.class); - - /** - * Key Identifier. - */ - private String keyId; - - /** - * JsonWebKey key type (kty). Possible values include: 'EC', 'EC-HSM', 'RSA', - * 'RSA-HSM', 'oct', and 'oct-HSM'. - */ - private KeyType keyType; - - /** - * The keyOps property. - */ - private List keyOps; - - /** - * RSA modulus. - */ - private byte[] n; - - /** - * RSA public exponent. - */ - private byte[] e; - - /** - * RSA private exponent, or the D component of an EC private key. - */ - private byte[] d; - - /** - * RSA Private Key Parameter. - */ - private byte[] dp; - - /** - * RSA Private Key Parameter. - */ - private byte[] dq; - - /** - * RSA Private Key Parameter. - */ - private byte[] qi; - - /** - * RSA secret prime. - */ - private byte[] p; - - /** - * RSA secret prime, with p & q. - */ - private byte[] q; - - /** - * Symmetric key. - */ - private byte[] k; - - /** - * HSM Token, used with Bring Your Own Key. - */ - private byte[] t; - - /** - * Elliptic curve name. For valid values, see KeyCurveName. Possible - * values include: 'P-256', 'P-384', 'P-521', and 'SECP256K1'. - */ - private KeyCurveName crv; - - /** - * X component of an EC public key. - */ - private byte[] x; - - /** - * Y component of an EC public key. - */ - private byte[] y; - - /** - * Creates a new instance of {@link JsonWebKey}. - */ - public JsonWebKey() { - } - - /** - * Get the kid value. - * - * @return the kid value - */ - public String getId() { - return this.keyId; - } - - /** - * Set the key identifier value. - * - * @param keyId The keyId value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setId(String keyId) { - this.keyId = keyId; - return this; - } - - /** - * Get the kty value. - * - * @return the kty value - */ - public KeyType getKeyType() { - return this.keyType; - } - - /** - * Set the key type value. - * - * @param keyType The key type - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setKeyType(KeyType keyType) { - this.keyType = keyType; - return this; - } - - /** - * Get the immutable key operations list. The list cannot be modified. - * - * @return the key operations list - */ - public List getKeyOps() { - return this.keyOps == null - ? Collections.unmodifiableList(new ArrayList()) - : Collections.unmodifiableList(this.keyOps); - } - - /** - * Set the keyOps value. - * - * @param keyOps The keyOps value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setKeyOps(List keyOps) { - this.keyOps = keyOps; - return this; - } - - /** - * Get the n value. - * - * @return the n value - */ - public byte[] getN() { - return CoreUtils.clone(this.n); - } - - /** - * Set the n value. - * - * @param n The n value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setN(byte[] n) { - this.n = CoreUtils.clone(n); - return this; - } - - /** - * Get the e value. - * - * @return the e value - */ - public byte[] getE() { - return CoreUtils.clone(this.e); - } - - /** - * Set the e value. - * - * @param e The e value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setE(byte[] e) { - this.e = CoreUtils.clone(e); - return this; - } - - /** - * Get the d value. - * - * @return the d value - */ - public byte[] getD() { - return CoreUtils.clone(this.d); - } - - /** - * Set the d value. - * - * @param d The d value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setD(byte[] d) { - this.d = CoreUtils.clone(d); - return this; - } - - /** - * Get the RSA Private Key Parameter value. - * - * @return the RSA Private Key Parameter value. - */ - public byte[] getDp() { - return CoreUtils.clone(this.dp); - } - - /** - * Set RSA Private Key Parameter value. - * - * @param dp The RSA Private Key Parameter value to set. - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setDp(byte[] dp) { - this.dp = CoreUtils.clone(dp); - return this; - } - - /** - * Get the RSA Private Key Parameter value. - * - * @return the RSA Private Key Parameter value. - */ - public byte[] getDq() { - return CoreUtils.clone(this.dq); - } - - /** - * Set RSA Private Key Parameter value . - * - * @param dq The RSA Private Key Parameter value to set. - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setDq(byte[] dq) { - this.dq = CoreUtils.clone(dq); - return this; - } - - /** - * Get the RSA Private Key Parameter value. - * - * @return the RSA Private Key Parameter value. - */ - public byte[] getQi() { - return CoreUtils.clone(this.qi); - } - - /** - * Set RSA Private Key Parameter value. - * - * @param qi The RSA Private Key Parameter value to set. - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setQi(byte[] qi) { - this.qi = CoreUtils.clone(qi); - return this; - } - - /** - * Get the RSA secret prime value. - * - * @return the RSA secret prime value. - */ - public byte[] getP() { - return CoreUtils.clone(this.p); - } - - /** - * Set the RSA secret prime value. - * - * @param p The RSA secret prime value. - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setP(byte[] p) { - this.p = CoreUtils.clone(p); - return this; - } - - /** - * Get RSA secret prime, with p < q value. - * - * @return the RSA secret prime, with p < q value. - */ - public byte[] getQ() { - return CoreUtils.clone(this.q); - } - - /** - * Set the RSA secret prime, with p < q value. - * - * @param q The the RSA secret prime, with p < q value to be set. - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setQ(byte[] q) { - this.q = CoreUtils.clone(q); - return this; - } - - /** - * Get Symmetric key value. - * - * @return the symmetric key value. - */ - public byte[] getK() { - return CoreUtils.clone(this.k); - } - - /** - * Set the Symmetric key value. - * - * @param k The symmetric key value to set. - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setK(byte[] k) { - this.k = CoreUtils.clone(k); - return this; - } - - /** - * Get HSM Token value, used with Bring Your Own Key. - * - * @return HSM Token, used with Bring Your Own Key. - */ - public byte[] getT() { - return CoreUtils.clone(this.t); - } - - /** - * Set HSM Token value, used with Bring Your Own Key. - * - * @param t The HSM Token value to set, used with Bring Your Own Key - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setT(byte[] t) { - this.t = CoreUtils.clone(t); - return this; - } - - @Override - public String toString() { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); - JsonWriter writer = JsonProviders.createWriter(baos)) { - this.toJson(writer).flush(); - return baos.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { - throw LOGGER.logExceptionAsError(new IllegalStateException(e)); - } - } - - /** - * Get the crv value. - * - * @return the crv value - */ - public KeyCurveName getCurveName() { - return this.crv; - } - - /** - * Set the crv value. - * - * @param crv The crv value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setCurveName(KeyCurveName crv) { - this.crv = crv; - return this; - } - - /** - * Get the x value. - * - * @return the x value - */ - public byte[] getX() { - return CoreUtils.clone(this.x); - } - - /** - * Set the x value. - * - * @param x The x value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setX(byte[] x) { - this.x = CoreUtils.clone(x); - return this; - } - - /** - * Get the y value. - * - * @return the y value - */ - public byte[] getY() { - return CoreUtils.clone(this.y); - } - - /** - * Set the y value. - * - * @param y The y value to set - * - * @return the JsonWebKey object itself. - */ - public JsonWebKey setY(byte[] y) { - this.y = CoreUtils.clone(y); - return this; - } - - /** - * Get the RSA public key spec value. - * - * @return the RSA public key spec value - */ - private RSAPublicKeySpec getRsaPublicKeySpec() { - - return new RSAPublicKeySpec(toBigInteger(n), toBigInteger(e)); - } - - /** - * Get the RSA private key spec value. - * - * @return the RSA private key spec value - */ - private RSAPrivateKeySpec getRsaPrivateKeySpec() { - - return new RSAPrivateCrtKeySpec(toBigInteger(n), toBigInteger(e), toBigInteger(d), toBigInteger(p), - toBigInteger(q), toBigInteger(dp), toBigInteger(dq), toBigInteger(qi)); - } - - /** - * Get the RSA public key value. - * - * @param provider The Java security provider. - * - * @return the RSA public key value - */ - private PublicKey getRsaPublicKey(Provider provider) { - - try { - RSAPublicKeySpec publicKeySpec = getRsaPublicKeySpec(); - KeyFactory factory - = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA"); - - return factory.generatePublic(publicKeySpec); - } catch (GeneralSecurityException e) { - throw LOGGER.logExceptionAsError(new IllegalStateException(e)); - } - } - - /** - * Get the RSA private key value. - * - * @param provider The Java security provider. - * - * @return the RSA private key value - */ - private PrivateKey getRsaPrivateKey(Provider provider) { - - try { - RSAPrivateKeySpec privateKeySpec = getRsaPrivateKeySpec(); - KeyFactory factory - = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA"); - - return factory.generatePrivate(privateKeySpec); - } catch (GeneralSecurityException e) { - throw LOGGER.logExceptionAsError(new IllegalStateException(e)); - } - } - - private static PublicKey getEcPublicKey(ECPoint ecPoint, ECParameterSpec curveSpec, Provider provider) { - // Create public key spec with given point - try { - ECPublicKeySpec pubSpec = new ECPublicKeySpec(ecPoint, curveSpec); - KeyFactory kf - = provider != null ? KeyFactory.getInstance("EC", provider) : KeyFactory.getInstance("EC", "SunEC"); - return (ECPublicKey) kf.generatePublic(pubSpec); - } catch (GeneralSecurityException e) { - throw new IllegalStateException(e); - } - } - - private static PrivateKey getEcPrivateKey(byte[] d, ECParameterSpec curveSpec, Provider provider) { - try { - ECPrivateKeySpec priSpec = new ECPrivateKeySpec(new BigInteger(1, d), curveSpec); - KeyFactory kf - = provider != null ? KeyFactory.getInstance("EC", provider) : KeyFactory.getInstance("EC", "SunEC"); - return (ECPrivateKey) kf.generatePrivate(priSpec); - } catch (GeneralSecurityException e) { - throw new IllegalStateException(e); - } - } - - /** - * Verifies if the key is an RSA key. - */ - private void checkRsaCompatible() { - if (!KeyType.RSA.equals(keyType) && !KeyType.RSA_HSM.equals(keyType)) { - throw LOGGER.logExceptionAsError(new UnsupportedOperationException("Not an RSA key")); - } - } - - private static byte[] toByteArray(BigInteger n) { - byte[] result = n.toByteArray(); - if (result[0] == 0) { - // The leading zero is used to let the number positive. Since RSA - // parameters are always positive, we remove it. - return Arrays.copyOfRange(result, 1, result.length); - } - return result; - } - - private static BigInteger toBigInteger(byte[] b) { - if (b[0] < 0) { - // RSA parameters are always positive numbers, so if the first byte - // is negative, we need to add a leading zero - // to make the entire BigInteger positive. - byte[] temp = new byte[1 + b.length]; - System.arraycopy(b, 0, temp, 1, b.length); - b = temp; - } - return new BigInteger(b); - } - - /** - * Converts RSA key pair to JSON web key. - * - * @param keyPair Tbe RSA key pair - * - * @return the JSON web key, converted from RSA key pair. - */ - public static JsonWebKey fromRsa(KeyPair keyPair) { - - RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate(); - JsonWebKey key = null; - - if (privateKey != null) { - - key = new JsonWebKey().setKeyType(KeyType.RSA) - .setN(toByteArray(privateKey.getModulus())) - .setE(toByteArray(privateKey.getPublicExponent())) - .setD(toByteArray(privateKey.getPrivateExponent())) - .setP(toByteArray(privateKey.getPrimeP())) - .setQ(toByteArray(privateKey.getPrimeQ())) - .setDp(toByteArray(privateKey.getPrimeExponentP())) - .setDq(toByteArray(privateKey.getPrimeExponentQ())) - .setQi(toByteArray(privateKey.getCrtCoefficient())); - } else { - - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - - key = new JsonWebKey().setKeyType(KeyType.RSA) - .setN(toByteArray(publicKey.getModulus())) - .setE(toByteArray(publicKey.getPublicExponent())) - .setD(null) - .setP(null) - .setQ(null) - .setDp(null) - .setDq(null) - .setQi(null); - } - - return key; - } - - /** - * Converts RSA key pair to JSON web key. - * - * @param keyPair Tbe RSA key pair - * @param keyOperations The key operations to set on the key - * - * @return the JSON web key, converted from RSA key pair. - */ - public static JsonWebKey fromRsa(KeyPair keyPair, List keyOperations) { - return fromRsa(keyPair).setKeyOps(keyOperations); - } - - /** - * Converts JSON web key to RSA key pair. - * - * @return RSA key pair - */ - public KeyPair toRsa() { - return this.toRsa(false); - } - - /** - * Converts JSON web key to RSA key pair and include the private key if set to - * true. - * - * @param includePrivateParameters true if the RSA key pair should include the private key. False otherwise. - * - * @return RSA key pair - */ - public KeyPair toRsa(boolean includePrivateParameters) { - return toRsa(includePrivateParameters, null); - } - - /** - * Converts JSON web key to RSA key pair and include the private key if set to - * true. - * - * @param provider The Java security provider. - * @param includePrivateParameters true if the RSA key pair should include the private key. False otherwise. - * - * @return RSA key pair - */ - public KeyPair toRsa(boolean includePrivateParameters, Provider provider) { - - // Must be RSA - checkRsaCompatible(); - - if (includePrivateParameters) { - return new KeyPair(getRsaPublicKey(provider), getRsaPrivateKey(provider)); - } else { - return new KeyPair(getRsaPublicKey(provider), null); - } - } - - /** - * Converts JSON web key to EC key pair and include the private key if set to - * true. - * - * @return EC key pair - */ - public KeyPair toEc() { - return toEc(false, null); - } - - /** - * Converts JSON web key to EC key pair and include the private key if set to - * true. - * - * @param includePrivateParameters true if the EC key pair should include the private key. False otherwise. - * - * @return EC key pair - */ - public KeyPair toEc(boolean includePrivateParameters) { - return toEc(includePrivateParameters, null); - } - - /** - * Converts JSON web key to EC key pair and include the private key if set to - * true. - * - * @param includePrivateParameters true if the EC key pair should include the private key. False otherwise. - * @param provider The Java security provider - * - * @return EC key pair - * - * @throws IllegalArgumentException if the key type is not EC or EC HSM - * @throws IllegalStateException if an instance of EC key pair cannot be generated - */ - public KeyPair toEc(boolean includePrivateParameters, Provider provider) { - if (!KeyType.EC.equals(keyType) && !KeyType.EC_HSM.equals(keyType)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("Not an EC key.")); - } - - if (provider == null) { - // Our default provider for this class. - provider = Security.getProvider("SunEC"); - } - - try { - KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", provider); - - ECGenParameterSpec gps = new ECGenParameterSpec(getCurveSpecName(crv)); - kpg.initialize(gps); - - // Generate dummy keypair to get parameter spec. - KeyPair keyPair = kpg.generateKeyPair(); - ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); - ECParameterSpec ecParameterSpec = publicKey.getParams(); - - ECPoint ecPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y)); - - KeyPair realKeyPair; - - if (includePrivateParameters) { - realKeyPair = new KeyPair(getEcPublicKey(ecPoint, ecParameterSpec, provider), - getEcPrivateKey(d, ecParameterSpec, provider)); - } else { - realKeyPair = new KeyPair(getEcPublicKey(ecPoint, ecParameterSpec, provider), null); - } - - return realKeyPair; - } catch (GeneralSecurityException e) { - throw LOGGER.logExceptionAsError(new IllegalStateException(e)); - } - } - - /** - * Converts EC key pair to JSON web key. - * - * @param keyPair The EC key pair - * @param provider The Java security provider - * - * @return the JSON web key, converted from EC key pair. - */ - public static JsonWebKey fromEc(KeyPair keyPair, Provider provider) { - ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); - JsonWebKey jsonWebKey = new JsonWebKey().setKeyType(KeyType.EC) - .setCurveName(getCurveFromKeyPair(keyPair, provider)) - .setX(publicKey.getW().getAffineX().toByteArray()) - .setY(publicKey.getW().getAffineY().toByteArray()) - .setKeyType(KeyType.EC); - ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate(); - - if (ecPrivateKey != null) { - jsonWebKey.setD(ecPrivateKey.getS().toByteArray()); - } - - return jsonWebKey; - } - - /** - * Converts EC key pair to JSON web key. - * - * @param keyPair The EC key pair - * @param provider The Java security provider - * @param keyOperations The key operations to set. - * - * @return the JSON web key, converted from EC key pair. - */ - public static JsonWebKey fromEc(KeyPair keyPair, Provider provider, List keyOperations) { - return fromEc(keyPair, provider).setKeyOps(keyOperations); - } - - // Matches the curve of the keyPair to supported curves. - private static KeyCurveName getCurveFromKeyPair(KeyPair keyPair, Provider provider) { - - try { - ECPublicKey key = (ECPublicKey) keyPair.getPublic(); - ECParameterSpec spec = key.getParams(); - EllipticCurve crv = spec.getCurve(); - - for (KeyCurveName curve : KNOWN_CURVE_NAMES) { - ECGenParameterSpec gps = new ECGenParameterSpec(getCurveSpecName(curve)); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", provider); - kpg.initialize(gps); - - // Generate dummy keypair to get parameter spec. - KeyPair apair = kpg.generateKeyPair(); - ECPublicKey apub = (ECPublicKey) apair.getPublic(); - ECParameterSpec aspec = apub.getParams(); - EllipticCurve acurve = aspec.getCurve(); - - // Matches the parameter spec - if (acurve.equals(crv)) { - return curve; - } - } - - // Did not find a supported curve. - throw new NoSuchAlgorithmException("Curve not supported."); - } catch (GeneralSecurityException e) { - throw new IllegalStateException(e); - } - } - - /** - * Converts AES key to JSON web key. - * - * @param secretKey The AES key - * - * @return the JSON web key, converted from AES key. - */ - public static JsonWebKey fromAes(SecretKey secretKey) { - if (secretKey == null) { - return null; - } - - return new JsonWebKey().setK(secretKey.getEncoded()).setKeyType(KeyType.OCT); - } - - /** - * Converts AES key to JSON web key. - * - * @param secretKey The AES key - * @param keyOperations The key operations to set - * - * @return the JSON web key, converted from AES key. - */ - public static JsonWebKey fromAes(SecretKey secretKey, List keyOperations) { - return fromAes(secretKey).setKeyOps(keyOperations); - } - - /** - * Converts JSON web key to AES key. - * - * @return AES key - */ - public SecretKey toAes() { - if (k == null) { - return null; - } - - return new SecretKeySpec(k, "AES"); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (obj instanceof JsonWebKey) { - return this.equals((JsonWebKey) obj); - } - - return false; - } - - /** - * Indicates whether some other {@link JsonWebKey} is "equal to" this one. - * - * @param jwk The other {@link JsonWebKey} to compare with. - * - * @return true if this {@link JsonWebKey} is the same as the jwk argument; - * false otherwise. - */ - public boolean equals(JsonWebKey jwk) { - if (jwk == null) { - return false; - } - - return Objects.equals(keyId, jwk.keyId) - && Objects.equals(keyType, jwk.keyType) - && Objects.equals(keyOps, jwk.keyOps) - && Objects.equals(crv, jwk.crv) - && Arrays.equals(k, jwk.k) - && Arrays.equals(n, jwk.n) - && Arrays.equals(e, jwk.e) - && Arrays.equals(d, jwk.d) - && Arrays.equals(dp, jwk.dp) - && Arrays.equals(dq, jwk.dq) - && Arrays.equals(qi, jwk.qi) - && Arrays.equals(p, jwk.p) - && Arrays.equals(q, jwk.q) - && Arrays.equals(x, jwk.x) - && Arrays.equals(y, jwk.y) - && Arrays.equals(t, jwk.t); - } - - /** - * Verifies whether the {@link JsonWebKey} has private key. - * - * @return true if the {@link JsonWebKey} has private key; false otherwise. - */ - public boolean hasPrivateKey() { - - if (KeyType.OCT.equals(keyType)) { - return k != null; - } else if (KeyType.RSA.equals(keyType) || KeyType.RSA_HSM.equals(keyType)) { - return (d != null && dp != null && dq != null && qi != null && p != null && q != null); - } else if (KeyType.EC.equals(keyType) || KeyType.EC_HSM.equals(keyType)) { - return (d != null); - } - - return false; - } - - /** - * Verifies whether the {@link JsonWebKey} is valid. - * - * @return true if the {@link JsonWebKey} is valid; false otherwise. - */ - public boolean isValid() { - if (keyType == null) { - return false; - } - - if (KeyType.OCT.equals(keyType) || KeyType.OCT_HSM.equals(keyType)) { - return isValidOctet(); - } else if (KeyType.RSA.equals(keyType)) { - return isValidRsa(); - } else if (KeyType.RSA_HSM.equals(keyType)) { - return isValidRsaHsm(); - } else if (KeyType.EC.equals(keyType)) { - return isValidEc(); - } else if (KeyType.EC_HSM.equals(keyType)) { - return isValidEcHsm(); - } - - return false; - } - - private boolean isValidOctet() { - return k != null; - } - - private boolean isValidRsa() { - if (n == null || e == null) { - return false; - } - - return hasPrivateKey() || (d == null && dp == null && dq == null && qi == null && p == null && q == null); - } - - private boolean isValidRsaHsm() { - // MAY have public key parameters - if ((n == null && e != null) || (n != null && e == null)) { - return false; - } - - // no private key - if (hasPrivateKey()) { - return false; - } - - // MUST have ( T || ( n && E ) ) - boolean tokenParameters = t != null; - boolean publicParameters = (n != null && e != null); - - if (tokenParameters && publicParameters) { - return false; - } - - return (tokenParameters || publicParameters); - } - - private boolean isValidEc() { - boolean ecPointParameters = (x != null && y != null); - - if (!ecPointParameters || crv == null) { - return false; - } - - return hasPrivateKey() || (d == null); - } - - private boolean isValidEcHsm() { - // MAY have public key parameters - boolean ecPointParameters = (x != null && y != null); - - if ((ecPointParameters && crv == null) || (!ecPointParameters && crv != null)) { - return false; - } - - // no private key - if (hasPrivateKey()) { - return false; - } - - // MUST have (T || (ecPointParameters && crv)) - boolean publicParameters = (ecPointParameters && crv != null); - boolean tokenParameters = t != null; - - if (tokenParameters && publicParameters) { - return false; - } - - return (tokenParameters || publicParameters); - } - - /** - * Clear key materials. - */ - public void clearMemory() { - zeroArray(k); - k = null; - zeroArray(n); - n = null; - zeroArray(e); - e = null; - zeroArray(d); - d = null; - zeroArray(dp); - dp = null; - zeroArray(dq); - dq = null; - zeroArray(qi); - qi = null; - zeroArray(p); - p = null; - zeroArray(q); - q = null; - zeroArray(t); - t = null; - zeroArray(x); - x = null; - zeroArray(y); - y = null; - } - - private static void zeroArray(byte[] bytes) { - if (bytes != null) { - Arrays.fill(bytes, (byte) 0); - } - } - - @Override - public int hashCode() { - int hashCode = 48313; // setting it to a random prime number - if (keyId != null) { - hashCode += keyId.hashCode(); - } - - if (KeyType.OCT.equals(keyType)) { - hashCode += hashCode(k); - } else if (KeyType.RSA.equals(keyType)) { - hashCode += hashCode(n); - } else if (KeyType.EC.equals(keyType)) { - hashCode += hashCode(x); - hashCode += hashCode(y); - hashCode += crv.hashCode(); - } else if (KeyType.RSA_HSM.equals(keyType) || KeyType.EC_HSM.equals(keyType)) { - hashCode += hashCode(t); - } - - return hashCode; - } - - private static int hashCode(byte[] obj) { - int hashCode = 0; - - if (obj == null || obj.length == 0) { - return 0; - } - - for (byte b : obj) { - hashCode = (hashCode << 3) | (hashCode >> 29) ^ b; - } - return hashCode; - } - - private static String getCurveSpecName(KeyCurveName curveName) { - if (curveName == null) { - return null; - } - - if (curveName == KeyCurveName.P_256) { - return "secp256r1"; - } else if (curveName == KeyCurveName.P_384) { - return "secp384r1"; - } else if (curveName == KeyCurveName.P_521) { - return "secp521r1"; - } else if (curveName == KeyCurveName.P_256K) { - return "secp256k1"; - } else { - return null; - } - } - - private static final List KNOWN_CURVE_NAMES - = Arrays.asList(KeyCurveName.P_256, KeyCurveName.P_384, KeyCurveName.P_521, KeyCurveName.P_256K); - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - - jsonWriter.writeStringField("kid", keyId); - jsonWriter.writeStringField("kty", Objects.toString(keyType, null)); - jsonWriter.writeArrayField("key_ops", keyOps, (writer, op) -> writer.writeString(Objects.toString(op, null))); - jsonWriter.writeStringField("n", KeyVaultKeysUtils.base64UrlJsonSerialization(n)); - jsonWriter.writeStringField("e", KeyVaultKeysUtils.base64UrlJsonSerialization(e)); - jsonWriter.writeStringField("d", KeyVaultKeysUtils.base64UrlJsonSerialization(d)); - jsonWriter.writeStringField("dp", KeyVaultKeysUtils.base64UrlJsonSerialization(dp)); - jsonWriter.writeStringField("dq", KeyVaultKeysUtils.base64UrlJsonSerialization(dq)); - jsonWriter.writeStringField("qi", KeyVaultKeysUtils.base64UrlJsonSerialization(qi)); - jsonWriter.writeStringField("p", KeyVaultKeysUtils.base64UrlJsonSerialization(p)); - jsonWriter.writeStringField("q", KeyVaultKeysUtils.base64UrlJsonSerialization(q)); - jsonWriter.writeStringField("k", KeyVaultKeysUtils.base64UrlJsonSerialization(k)); - jsonWriter.writeStringField("key_hsm", KeyVaultKeysUtils.base64UrlJsonSerialization(t)); - jsonWriter.writeStringField("crv", Objects.toString(crv, null)); - jsonWriter.writeStringField("x", KeyVaultKeysUtils.base64UrlJsonSerialization(x)); - jsonWriter.writeStringField("y", KeyVaultKeysUtils.base64UrlJsonSerialization(y)); - - return jsonWriter.writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link JsonWebKey}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link JsonWebKey} that the JSON stream represented, may return null. - * @throws IOException If a {@link JsonWebKey} fails to be read from the {@code jsonReader}. - */ - public static JsonWebKey fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - JsonWebKey key = new JsonWebKey(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kid".equals(fieldName)) { - key.keyId = reader.getString(); - } else if ("kty".equals(fieldName)) { - key.keyType = KeyType.fromString(reader.getString()); - } else if ("key_ops".equals(fieldName)) { - key.keyOps = reader.readArray(arrayReader -> KeyOperation.fromString(arrayReader.getString())); - } else if ("n".equals(fieldName)) { - key.n = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("e".equals(fieldName)) { - key.e = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("d".equals(fieldName)) { - key.d = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("dp".equals(fieldName)) { - key.dp = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("dq".equals(fieldName)) { - key.dq = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("qi".equals(fieldName)) { - key.qi = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("p".equals(fieldName)) { - key.p = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("q".equals(fieldName)) { - key.q = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("k".equals(fieldName)) { - key.k = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("key_hsm".equals(fieldName)) { - key.t = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("crv".equals(fieldName)) { - key.crv = KeyCurveName.fromString(reader.getString()); - } else if ("x".equals(fieldName)) { - key.x = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else if ("y".equals(fieldName)) { - key.y = KeyVaultKeysUtils.base64UrlJsonDeserialization(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return key; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java deleted file mode 100644 index 6805836416ed..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. -package com.azure.security.keyvault.keys.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Elliptic curve name. - */ -public final class KeyCurveName extends ExpandableStringEnum { - - /** - * The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. - */ - public static final KeyCurveName P_256 = fromString("P-256"); - - /** - * The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. - */ - public static final KeyCurveName P_384 = fromString("P-384"); - - /** - * The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. - */ - public static final KeyCurveName P_521 = fromString("P-521"); - - /** - * The SECG SECP256K1 elliptic curve. - */ - public static final KeyCurveName P_256K = fromString("P-256K"); - - /** - * Creates a new instance of KeyCurveName value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public KeyCurveName() { - } - - /** - * Creates or finds a KeyCurveName from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyCurveName. - */ - public static KeyCurveName fromString(String name) { - return fromString(name, KeyCurveName.class); - } - - /** - * Gets known KeyCurveName values. - * - * @return known KeyCurveName values. - */ - public static Collection values() { - return values(KeyCurveName.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java deleted file mode 100644 index d62ffec53bdb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. -package com.azure.security.keyvault.keys.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The encryption algorithm to use to protected the exported key material. - */ -public final class KeyExportEncryptionAlgorithm extends ExpandableStringEnum { - - /** - * Static value CKM_RSA_AES_KEY_WRAP for KeyExportEncryptionAlgorithm. - */ - public static final KeyExportEncryptionAlgorithm CKM_RSA_AES_KEY_WRAP = fromString("CKM_RSA_AES_KEY_WRAP"); - - /** - * Static value RSA_AES_KEY_WRAP_256 for KeyExportEncryptionAlgorithm. - */ - public static final KeyExportEncryptionAlgorithm RSA_AES_KEY_WRAP_256 = fromString("RSA_AES_KEY_WRAP_256"); - - /** - * Static value RSA_AES_KEY_WRAP_384 for KeyExportEncryptionAlgorithm. - */ - public static final KeyExportEncryptionAlgorithm RSA_AES_KEY_WRAP_384 = fromString("RSA_AES_KEY_WRAP_384"); - - /** - * Creates a new instance of KeyExportEncryptionAlgorithm value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public KeyExportEncryptionAlgorithm() { - } - - /** - * Creates or finds a KeyExportEncryptionAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyExportEncryptionAlgorithm. - */ - public static KeyExportEncryptionAlgorithm fromString(String name) { - return fromString(name, KeyExportEncryptionAlgorithm.class); - } - - /** - * Gets known KeyExportEncryptionAlgorithm values. - * - * @return known KeyExportEncryptionAlgorithm values. - */ - public static Collection values() { - return values(KeyExportEncryptionAlgorithm.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java deleted file mode 100644 index 4028bd25bb96..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * JSON web key operations. For more information, see JsonWebKeyOperation. - */ -public final class KeyOperation extends ExpandableStringEnum { - /** - * Static value encrypt for KeyOperation. - */ - public static final KeyOperation ENCRYPT = fromString("encrypt"); - - /** - * Static value decrypt for KeyOperation. - */ - public static final KeyOperation DECRYPT = fromString("decrypt"); - - /** - * Static value sign for KeyOperation. - */ - public static final KeyOperation SIGN = fromString("sign"); - - /** - * Static value verify for KeyOperation. - */ - public static final KeyOperation VERIFY = fromString("verify"); - - /** - * Static value wrapKey for KeyOperation. - */ - public static final KeyOperation WRAP_KEY = fromString("wrapKey"); - - /** - * Static value unwrapKey for KeyOperation. - */ - public static final KeyOperation UNWRAP_KEY = fromString("unwrapKey"); - - /** - * Static value import for KeyOperation. - */ - public static final KeyOperation IMPORT = fromString("import"); - - /** - * Creates a new instance of KeyOperation value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public KeyOperation() { - } - - /** - * Creates or finds a KeyOperation from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyOperation. - */ - public static KeyOperation fromString(String name) { - return fromString(name, KeyOperation.class); - } - - /** - * Gets known KeyOperation values. - * - * @return known KeyOperation values. - */ - public static Collection values() { - return values(KeyOperation.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyProperties.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyProperties.java deleted file mode 100644 index c681851d8b26..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyProperties.java +++ /dev/null @@ -1,446 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.KeyAsyncClient; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.implementation.KeyPropertiesHelper; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; - -import java.io.IOException; -import java.time.OffsetDateTime; -import java.util.Map; - -/** - * {@link KeyProperties} is the resource containing all the properties of the key except its {@link JsonWebKey} - * material. It is managed by the Key Service. - * - * @see KeyClient - * @see KeyAsyncClient - */ -@Fluent -public class KeyProperties implements JsonSerializable { - static { - KeyPropertiesHelper.setAccessor(new KeyPropertiesHelper.KeyPropertiesAccessor() { - @Override - public void setCreatedOn(KeyProperties keyProperties, OffsetDateTime createdOn) { - keyProperties.createdOn = createdOn; - } - - @Override - public void setUpdatedOn(KeyProperties keyProperties, OffsetDateTime updatedOn) { - keyProperties.updatedOn = updatedOn; - } - - @Override - public void setRecoveryLevel(KeyProperties keyProperties, String recoveryLevel) { - keyProperties.recoveryLevel = recoveryLevel; - } - - @Override - public void setName(KeyProperties keyProperties, String name) { - keyProperties.name = name; - } - - @Override - public void setVersion(KeyProperties keyProperties, String version) { - keyProperties.version = version; - } - - @Override - public void setId(KeyProperties keyProperties, String id) { - keyProperties.id = id; - } - - @Override - public void setManaged(KeyProperties keyProperties, Boolean managed) { - keyProperties.managed = managed; - } - - @Override - public void setRecoverableDays(KeyProperties keyProperties, Integer recoverableDays) { - keyProperties.recoverableDays = recoverableDays; - } - - @Override - public void setHsmPlatform(KeyProperties keyProperties, String hsmPlatform) { - keyProperties.hsmPlatform = hsmPlatform; - } - }); - } - /** - * Determines whether the object is enabled. - */ - Boolean enabled; - - /** - * Indicates if the private key can be exported. - */ - Boolean exportable; - - /** - * Not before date in UTC. - */ - OffsetDateTime notBefore; - - /** - * The key version. - */ - String version; - - /** - * Expiry date in UTC. - */ - OffsetDateTime expiresOn; - - /** - * Creation time in UTC. - */ - OffsetDateTime createdOn; - - /** - * Last updated time in UTC. - */ - OffsetDateTime updatedOn; - - /** - * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains - * 'Purgeable', the key can be permanently deleted by a privileged user; otherwise, only the system can purge the - * key, at the end of the retention interval. Possible values include: 'Purgeable', 'Recoverable+Purgeable', - * 'Recoverable', 'Recoverable+ProtectedSubscription'. - */ - String recoveryLevel; - - /** - * The key name. - */ - String name; - - /** - * Key identifier. - */ - String id; - - /** - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /** - * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will - * be true. - */ - Boolean managed; - - /** - * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. - */ - Integer recoverableDays; - - /** - * The policy rules under which the key can be exported. - */ - KeyReleasePolicy releasePolicy; - - /** - * The underlying HSM Platform the key was generated with. - */ - private String hsmPlatform; - - /** - * Creates a new instance of {@link KeyProperties}. - */ - public KeyProperties() { - } - - /** - * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. - * - * @return The recoverable days. - */ - public Integer getRecoverableDays() { - return recoverableDays; - } - - /** - * Get the policy rules under which the key can be exported. - * - * @return The policy rules under which the key can be exported. - */ - public KeyReleasePolicy getReleasePolicy() { - return this.releasePolicy; - } - - /** - * Set the policy rules under which the key can be exported. - * - * @param releasePolicy The policy rules to set. - * - * @return The updated {@link KeyProperties} object. - */ - public KeyProperties setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - - return this; - } - - /** - * Get the key recovery level. - * - * @return The key recovery level. - */ - public String getRecoveryLevel() { - return this.recoveryLevel; - } - - /** - * Get the key name. - * - * @return The name of the key. - */ - public String getName() { - return this.name; - } - - /** - * Get the enabled value. - * - * @return The enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set a value that indicates if the key is enabled. - * - * @param enabled The enabled value to set. - * - * @return The updated {@link KeyProperties} object. - */ - public KeyProperties setEnabled(Boolean enabled) { - this.enabled = enabled; - - return this; - } - - /** - * Get a flag that indicates if the private key can be exported. - * - * @return A flag that indicates if the private key can be exported. - */ - public Boolean isExportable() { - return this.exportable; - } - - /** - * Set a flag that indicates if the private key can be exported. - * - * @param exportable A flag that indicates if the private key can be exported. - * - * @return The updated {@link KeyProperties} object. - */ - public KeyProperties setExportable(Boolean exportable) { - this.exportable = exportable; - - return this; - } - - /** - * Get the {@link OffsetDateTime key's notBefore time} in UTC. - * - * @return The {@link OffsetDateTime key's notBefore time} in UTC. - */ - public OffsetDateTime getNotBefore() { - return notBefore; - } - - /** - * Set the {@link OffsetDateTime key's notBefore time} in UTC. - * - * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. - * - * @return The updated {@link KeyProperties} object. - */ - public KeyProperties setNotBefore(OffsetDateTime notBefore) { - this.notBefore = notBefore; - - return this; - } - - /** - * Get the {@link OffsetDateTime key expiration time} in UTC. - * - * @return The {@link OffsetDateTime key expiration time} in UTC. - */ - public OffsetDateTime getExpiresOn() { - return this.expiresOn; - } - - /** - * Set the {@link OffsetDateTime key expiration time} in UTC. - * - * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. - * - * @return The updated {@link KeyProperties} object. - */ - public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { - this.expiresOn = expiresOn; - - return this; - } - - /** - * Get the {@link OffsetDateTime time at which key was created} in UTC. - * - * @return The {@link OffsetDateTime time at which key was created} in UTC. - */ - public OffsetDateTime getCreatedOn() { - return createdOn; - } - - /** - * Get the {@link OffsetDateTime time at which key was last updated} in UTC. - * - * @return The {@link OffsetDateTime time at which key was last updated} in UTC. - */ - public OffsetDateTime getUpdatedOn() { - return updatedOn; - } - - /** - * Get the key identifier. - * - * @return The key identifier. - */ - public String getId() { - return this.id; - } - - /** - * Get the tags associated with the key. - * - * @return The tag names and values. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags to be associated with the key. - * - * @param tags The tags to set. - * - * @return The updated {@link KeyProperties} object. - */ - public KeyProperties setTags(Map tags) { - this.tags = tags; - - return this; - } - - /** - * Get the managed value. - * - * @return The managed value. - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Get the version of the key. - * - * @return The version of the key. - */ - public String getVersion() { - return this.version; - } - - /** - * Get the underlying HSM Platform the key was generated with. - * - * @return The key's underlying HSM Platform. - */ - public String getHsmPlatform() { - return hsmPlatform; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("kid", id) - .writeMapField("tags", tags, JsonWriter::writeString) - .writeJsonField("release_policy", releasePolicy) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link KeyProperties}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link KeyProperties} that the JSON stream represented, may return null. - * @throws IOException If a {@link KeyProperties} fails to be read from the {@code jsonReader}. - */ - public static KeyProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyProperties properties = new KeyProperties(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kid".equals(fieldName)) { - properties.id = reader.getString(); - KeyVaultKeysUtils.unpackId(properties.id, name -> properties.name = name, - version -> properties.version = version); - } else if ("tags".equals(fieldName)) { - properties.tags = reader.readMap(JsonReader::getString); - } else if ("immutable".equals(fieldName)) { - properties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("recoverableDays".equals(fieldName)) { - properties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("release_policy".equals(fieldName)) { - properties.releasePolicy = KeyReleasePolicy.fromJson(reader); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - while (reader.nextToken() != JsonToken.END_OBJECT) { - fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - properties.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("exportable".equals(fieldName)) { - properties.exportable = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - properties.notBefore = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("exp".equals(fieldName)) { - properties.expiresOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("created".equals(fieldName)) { - properties.createdOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("updated".equals(fieldName)) { - properties.updatedOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("recoveryLevel".equals(fieldName)) { - properties.recoveryLevel = reader.getString(); - } else if ("recoverableDays".equals(fieldName)) { - properties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("hsmPlatform".equals(fieldName)) { - properties.hsmPlatform = reader.getString(); - } else { - reader.skipChildren(); - } - } - } else { - reader.skipChildren(); - } - } - - return properties; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyReleasePolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyReleasePolicy.java deleted file mode 100644 index 97dfe172c668..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyReleasePolicy.java +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.BinaryData; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.util.Base64; -import java.util.Objects; - -/** - * A model that represents the policy rules under which the key can be exported. - */ -@Fluent -public final class KeyReleasePolicy implements JsonSerializable { - /** - * The policy rules under which the key can be released. Encoded based on the {@link KeyReleasePolicy#contentType}. - *

- * For more information regarding the release policy grammar for Azure Key Vault, please refer to: - * - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar. - * - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar. - */ - private final BinaryData encodedPolicy; - - /* - * Content type and version of key release policy. - */ - private String contentType; - - /* - * Defines the mutability state of the policy. Once marked immutable on the service side, this flag cannot be reset - * and the policy cannot be changed under any circumstances. - */ - private Boolean immutable; - - KeyReleasePolicy(BinaryData encodedPolicy, boolean ignored) { - this.encodedPolicy = null; - } - - /** - * Creates an instance of {@link KeyReleasePolicy}. - * - * @param encodedPolicy The policy rules under which the key can be released. Encoded based on the - * {@link KeyReleasePolicy#contentType}. - *

- * For more information regarding the release policy grammar for Azure Key Vault, please refer to: - * - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar. - * - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar. - */ - public KeyReleasePolicy(BinaryData encodedPolicy) { - Objects.requireNonNull(encodedPolicy, "'encodedPolicy' cannot be null."); - - this.encodedPolicy = encodedPolicy; - } - - /** - * Get a blob encoding the policy rules under which the key can be released. - * - * @return encodedPolicy The policy rules under which the key can be released. Encoded based on the - * {@link KeyReleasePolicy#contentType}. - *

- * For more information regarding the release policy grammar for Azure Key Vault, please refer to: - * - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar. - * - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar. - */ - public BinaryData getEncodedPolicy() { - return encodedPolicy; - } - - /** - * Get the content type and version of key release policy. - * - * @return The content type and version of key release policy. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the content type and version of key release policy. - * - *

The service default is "application/json; charset=utf-8".

- * - * @param contentType The content type and version of key release policy to set. - * - * @return The updated {@link KeyReleasePolicy} object. - */ - public KeyReleasePolicy setContentType(String contentType) { - this.contentType = contentType; - - return this; - } - - /** - * Get a value indicating if the policy is immutable. Once marked immutable on the service side, this flag cannot - * be reset and the policy cannot be changed under any circumstances. - * - * @return If the {@link KeyReleasePolicy} is immutable. - */ - public Boolean isImmutable() { - return this.immutable; - } - - /** - * Get a value indicating if the policy is immutable. Defines the mutability state of the policy. Once marked - * immutable on the service side, this flag cannot be reset and the policy cannot be changed under any - * circumstances. - * - * @param immutable The immutable value to set. - * @return The updated {@link KeyReleasePolicy} object. - */ - public KeyReleasePolicy setImmutable(Boolean immutable) { - this.immutable = immutable; - - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - - String encodedPolicyText; - if (encodedPolicy == null) { - encodedPolicyText = null; - } else { - byte[] bytes = encodedPolicy.toBytes(); - - if (bytes == null) { - encodedPolicyText = null; - } else if (bytes.length == 0) { - encodedPolicyText = ""; - } else { - encodedPolicyText = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); - } - } - - jsonWriter.writeStringField("data", encodedPolicyText); - jsonWriter.writeStringField("contentType", contentType); - jsonWriter.writeBooleanField("immutable", immutable); - - return jsonWriter.writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link KeyReleasePolicy}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link KeyReleasePolicy} that the JSON stream represented, may return null. - * @throws IOException If a {@link KeyReleasePolicy} fails to be read from the {@code jsonReader}. - */ - public static KeyReleasePolicy fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - BinaryData encodedPolicy = null; - String contentType = null; - Boolean immutable = null; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("data".equals(fieldName)) { - encodedPolicy - = reader.getNullable(nonNullReader -> BinaryData.fromString(nonNullReader.getString())); - } else if ("contentType".equals(fieldName)) { - contentType = reader.getString(); - } else if ("immutable".equals(fieldName)) { - immutable = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return new KeyReleasePolicy(encodedPolicy, false).setContentType(contentType).setImmutable(immutable); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationLifetimeAction.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationLifetimeAction.java deleted file mode 100644 index 6238d1769b4a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationLifetimeAction.java +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.implementation.KeyRotationLifetimeActionHelper; -import com.azure.security.keyvault.keys.implementation.models.LifetimeActionsTrigger; -import com.azure.security.keyvault.keys.implementation.models.LifetimeActionsType; - -import java.io.IOException; - -/** - * Represents an action that will be performed by Key Vault over the lifetime of a key. - */ -@Fluent -public final class KeyRotationLifetimeAction implements JsonSerializable { - static { - KeyRotationLifetimeActionHelper - .setAccessor(new KeyRotationLifetimeActionHelper.KeyRotationLifetimeActionAccessor() { - @Override - public KeyRotationLifetimeAction createLifetimeAction(LifetimeActionsTrigger trigger, - LifetimeActionsType actionsType) { - return new KeyRotationLifetimeAction(trigger, actionsType); - } - - @Override - public LifetimeActionsTrigger getTrigger(KeyRotationLifetimeAction lifetimeAction) { - return lifetimeAction.trigger; - } - - @Override - public LifetimeActionsType getActionType(KeyRotationLifetimeAction lifetimeAction) { - return lifetimeAction.actionType; - } - }); - } - - private final LifetimeActionsTrigger trigger; - - private final LifetimeActionsType actionType; - - /** - * Creates a {@link KeyRotationLifetimeAction}. - * - * @param action The {@link KeyRotationPolicyAction policy action}. - */ - public KeyRotationLifetimeAction(KeyRotationPolicyAction action) { - this.actionType = new LifetimeActionsType().setType(action); - this.trigger = new LifetimeActionsTrigger(); - } - - private KeyRotationLifetimeAction(LifetimeActionsTrigger trigger, LifetimeActionsType actionsType) { - this.trigger = trigger; - this.actionType = actionsType; - } - - /** - * Get the {@link KeyRotationPolicyAction policy action}. - * - * @return The {@link KeyRotationPolicyAction policy action}. - */ - public KeyRotationPolicyAction getAction() { - return this.actionType.getType(); - } - - /** - * Get the time after creation to attempt to rotate in ISO 8601 duration format. For example, 90 days would be - * "P90D", 3 months would be "P3M" and 1 year and 10 days would be "P1Y10D". See - * Wikipedia for more information on ISO 8601 durations. - * - * @return The time after creation to attempt to rotate in ISO duration format. - */ - public String getTimeAfterCreate() { - return this.trigger.getTimeAfterCreate(); - } - - /** - * Set the time after creation to attempt to rotate in ISO 8601 duration format. For example, 90 days would be - * "P90D", 3 months would be "P3M" and 1 year and 10 days would be "P1Y10D". See - * Wikipedia for more information on ISO 8601 durations. - * - * @param timeAfterCreate The time after creation to attempt to rotate in ISO duration format. - * - * @return The updated {@link KeyRotationLifetimeAction} object. - */ - public KeyRotationLifetimeAction setTimeAfterCreate(String timeAfterCreate) { - this.trigger.setTimeAfterCreate(timeAfterCreate); - - return this; - } - - /** - * Get the time before expiry to attempt to rotate or notify in ISO 8601 duration format. For example, 90 days would - * be "P90D", 3 months would be "P3M" and 1 year and 10 days would be "P1Y10D". See - * Wikipedia for more information on ISO 8601 durations. - * - * @return The time before expiry to attempt to rotate or notify in ISO duration format. - */ - public String getTimeBeforeExpiry() { - return this.trigger.getTimeBeforeExpiry(); - } - - /** - * Set the time before expiry to attempt to rotate or notify in ISO 8601 duration format. For example, 90 days would - * be "P90D", 3 months would be "P3M" and 1 year and 10 days would be "P1Y10D". See - * Wikipedia for more information on ISO 8601 durations. - * - * @param timeBeforeExpiry The time before expiry to attempt to rotate or notify in ISO duration format. - * - * @return The updated {@link KeyRotationLifetimeAction} object. - */ - public KeyRotationLifetimeAction setTimeBeforeExpiry(String timeBeforeExpiry) { - this.trigger.setTimeBeforeExpiry(timeBeforeExpiry); - - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeJsonField("trigger", trigger) - .writeJsonField("action", actionType) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link KeyReleasePolicy}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link KeyReleasePolicy} that the JSON stream represented, may return null. - * @throws IOException If a {@link KeyReleasePolicy} fails to be read from the {@code jsonReader}. - */ - public static KeyRotationLifetimeAction fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - LifetimeActionsTrigger trigger = null; - LifetimeActionsType actionType = null; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("trigger".equals(fieldName)) { - trigger = LifetimeActionsTrigger.fromJson(reader); - } else if ("action".equals(fieldName)) { - actionType = LifetimeActionsType.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return new KeyRotationLifetimeAction(trigger, actionType); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicy.java deleted file mode 100644 index 47447c99798f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicy.java +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.security.keyvault.keys.implementation.KeyRotationLifetimeActionHelper; -import com.azure.security.keyvault.keys.implementation.KeyRotationPolicyHelper; -import com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicyAttributes; -import com.azure.security.keyvault.keys.implementation.models.LifetimeActions; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.List; - -/** - * The complete key rotation policy that belongs to a key. - */ -public final class KeyRotationPolicy { - static { - KeyRotationPolicyHelper.setAccessor(new KeyRotationPolicyHelper.KeyRotationPolicyAccessor() { - @Override - public KeyRotationPolicy - createPolicy(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy impl) { - return new KeyRotationPolicy(impl); - } - - @Override - public com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy - getImpl(KeyRotationPolicy policy) { - return policy.impl; - } - }); - } - - private final com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy impl; - - private List lifetimeActions; - - /** - * Creates an instance of {@link KeyRotationPolicy}. - */ - public KeyRotationPolicy() { - this(new com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy()); - } - - KeyRotationPolicy(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy impl) { - this.impl = impl; - } - - /** - * Get the identifier of the {@link KeyRotationPolicy policy}. - * - *

May be undefined if a {@link KeyRotationPolicy policy} has not been explicitly set.

- * - * @return The identifier of the {@link KeyRotationPolicy policy}. - */ - public String getId() { - return impl.getId(); - } - - /** - * Get the actions that will be performed by Key Vault over the lifetime of a key. - * - *

You may also pass an empty array to restore to its default values.

- * - * @return The {@link KeyRotationLifetimeAction actions} in this {@link KeyRotationPolicy policy}. - */ - public List getLifetimeActions() { - if (this.lifetimeActions == null && impl.getLifetimeActions() != null) { - List mappedActions = new ArrayList<>(impl.getLifetimeActions().size()); - - for (LifetimeActions action : impl.getLifetimeActions()) { - KeyRotationLifetimeAction mappedAction - = KeyRotationLifetimeActionHelper.createLifetimeAction(action.getTrigger(), action.getAction()); - - mappedActions.add(mappedAction); - } - - this.lifetimeActions = mappedActions; - } - - return this.lifetimeActions; - } - - /** - * Set the actions that will be performed by Key Vault over the lifetime of a key. - * - *

You may also pass an empty array to restore to its default values.

- * - * @param lifetimeActions The {@link KeyRotationLifetimeAction actions} to set. - * - * @return The updated {@link KeyRotationPolicy} object. - */ - public KeyRotationPolicy setLifetimeActions(List lifetimeActions) { - if (lifetimeActions == null) { - this.lifetimeActions = null; - impl.setLifetimeActions(null); - return this; - } - - List mappedActions = new ArrayList<>(lifetimeActions.size()); - - for (KeyRotationLifetimeAction action : lifetimeActions) { - mappedActions.add(new LifetimeActions().setAction(KeyRotationLifetimeActionHelper.getActionType(action)) - .setTrigger(KeyRotationLifetimeActionHelper.getTrigger(action))); - } - - this.lifetimeActions = lifetimeActions; - impl.setLifetimeActions(mappedActions); - - return this; - } - - /** - * Get the optional key expiration period used to define the duration after which a newly rotated key will expire. - * It should be at least 28 days and should be defined as an ISO 8601 duration. For example, 90 days would be - * "P90D", 3 months would be "P3M" and 1 year and 10 days would be "P1Y10D". See - * Wikipedia for more information on ISO 8601 durations. - * - * @return The expiration time in ISO 8601 format. - */ - public String getExpiresIn() { - return impl.getAttributes() == null ? null : impl.getAttributes().getExpiryTime(); - } - - /** - * Set the optional key expiration period used to define the duration after which a newly rotated key will expire. - * It should be at least 28 days and should be defined as an ISO 8601 duration. For example, 90 days would be - * "P90D", 3 months would be "P3M" and 1 year and 10 days would be "P1Y10D". See - * Wikipedia for more information on ISO 8601 durations. - * - * @param expiresIn The expiration time to set in ISO 8601 duration format. - * - * @return The updated {@link KeyRotationPolicy} object. - */ - public KeyRotationPolicy setExpiresIn(String expiresIn) { - if (impl.getAttributes() == null) { - impl.setAttributes(new KeyRotationPolicyAttributes()); - } - - impl.getAttributes().setExpiryTime(expiresIn); - - return this; - } - - /** - * Get the {@link KeyRotationPolicy policy's} created time in UTC. - * - *

May be undefined if a {@link KeyRotationPolicy policy} has not been explicitly set.

- * - * @return The {@link KeyRotationPolicy policy's} created time in UTC. - */ - public OffsetDateTime getCreatedOn() { - return impl.getAttributes() == null ? null : impl.getAttributes().getCreated(); - } - - /** - * Get the {@link KeyRotationPolicy policy's} last updated time in UTC. - * - *

May be undefined if a {@link KeyRotationPolicy policy} has not been explicitly set.

- * - * @return The {@link KeyRotationPolicy policy's} last updated time in UTC. - */ - public OffsetDateTime getUpdatedOn() { - return impl.getAttributes() == null ? null : impl.getAttributes().getUpdated(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java deleted file mode 100644 index 63246059c599..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.models; - -/** - * The type of the action. The value should be compared case-insensitively. - */ -public enum KeyRotationPolicyAction { - /** - * Rotate the key based on the key policy. - */ - ROTATE("Rotate"), - - /** - * Trigger Event Grid events. Defaults to 30 days before expiry. Key Vault only. - */ - NOTIFY("Notify"); - - /** - * The actual serialized value for a KeyRotationPolicyAction instance. - */ - private final String value; - - KeyRotationPolicyAction(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a KeyRotationPolicyAction instance. - * - * @param value the serialized value to parse. - * @return the parsed KeyRotationPolicyAction object, or null if unable to parse. - */ - public static KeyRotationPolicyAction fromString(String value) { - if (value == null) { - return null; - } - KeyRotationPolicyAction[] items = KeyRotationPolicyAction.values(); - for (KeyRotationPolicyAction item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java deleted file mode 100644 index 8994aedea1c0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. -package com.azure.security.keyvault.keys.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ -public final class KeyType extends ExpandableStringEnum { - - /** - * Elliptic Curve. - */ - public static final KeyType EC = fromString("EC"); - - /** - * Elliptic Curve with a private key which is stored in the HSM. - */ - public static final KeyType EC_HSM = fromString("EC-HSM"); - - /** - * RSA (https://tools.ietf.org/html/rfc3447). - */ - public static final KeyType RSA = fromString("RSA"); - - /** - * RSA with a private key which is stored in the HSM. - */ - public static final KeyType RSA_HSM = fromString("RSA-HSM"); - - /** - * Octet sequence (used to represent symmetric keys). - */ - public static final KeyType OCT = fromString("oct"); - - /** - * Octet sequence (used to represent symmetric keys) which is stored the HSM. - */ - public static final KeyType OCT_HSM = fromString("oct-HSM"); - - /** - * Creates a new instance of KeyType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public KeyType() { - } - - /** - * Creates or finds a KeyType from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyType. - */ - public static KeyType fromString(String name) { - return fromString(name, KeyType.class); - } - - /** - * Gets known KeyType values. - * - * @return known KeyType values. - */ - public static Collection values() { - return values(KeyType.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKey.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKey.java deleted file mode 100644 index e59462f4f4e6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKey.java +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.KeyAsyncClient; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeyHelper; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; - -import java.io.IOException; -import java.util.List; - -/** - * Key is the resource consisting of name, {@link JsonWebKey} and its attributes specified in {@link KeyProperties}. - * It is managed by Key Service. - * - * @see KeyClient - * @see KeyAsyncClient - */ -@Fluent -public class KeyVaultKey implements JsonSerializable { - static { - KeyVaultKeyHelper.setAccessor(KeyVaultKey::new); - } - - /** - * The Json Web Key. - */ - private final JsonWebKey key; - - /** - * The key properties. - */ - final KeyProperties properties; - - KeyVaultKey() { - this.key = null; - this.properties = new KeyProperties(); - } - - /** - * Creates an instance of {@link KeyVaultKey}. - * - * @param jsonWebKey The {@link JsonWebKey} to be used for crypto operations. - */ - KeyVaultKey(JsonWebKey jsonWebKey) { - this.key = jsonWebKey; - this.properties = new KeyProperties(); - } - - KeyVaultKey(JsonWebKey jsonWebKey, KeyProperties properties) { - this.key = jsonWebKey; - this.properties = properties; - } - - /** - * Get the JSON Web Key. - * - * @return The JSON Web Key. - */ - public JsonWebKey getKey() { - return this.key; - } - - /** - * Get the key properties. - * - * @return The key properties. - */ - public KeyProperties getProperties() { - return this.properties; - } - - /** - * Get the key identifier. - * - * @return The key identifier. - */ - public String getId() { - return properties.getId(); - } - - /** - * Get the key name. - * - * @return The key name. - */ - public String getName() { - return properties.getName(); - } - - /** - * Get the key type. - * - * @return The key type. - */ - public KeyType getKeyType() { - return key.getKeyType(); - } - - /** - * Get the key operations. - * - * @return The key operations. - */ - public List getKeyOperations() { - return key.getKeyOps(); - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject().writeJsonField("key", key).writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link KeyVaultKey}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link KeyVaultKey} that the JSON stream represented, may return null. - * @throws IOException If a {@link KeyVaultKey} fails to be read from the {@code jsonReader}. - */ - public static KeyVaultKey fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - JsonWebKey webKey = null; - KeyProperties properties = new KeyProperties(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("key".equals(fieldName)) { - webKey = JsonWebKey.fromJson(reader); - KeyVaultKeysUtils.unpackId(webKey.getId(), name -> properties.name = name, - version -> properties.version = version); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - while (reader.nextToken() != JsonToken.END_OBJECT) { - fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - properties.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("exportable".equals(fieldName)) { - properties.exportable = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - properties.notBefore = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("exp".equals(fieldName)) { - properties.expiresOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("created".equals(fieldName)) { - properties.createdOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("updated".equals(fieldName)) { - properties.updatedOn = reader.getNullable(KeyVaultKeysUtils::epochToOffsetDateTime); - } else if ("recoveryLevel".equals(fieldName)) { - properties.recoveryLevel = reader.getString(); - } else if ("recoverableDays".equals(fieldName)) { - properties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - } else if ("tags".equals(fieldName)) { - properties.setTags(reader.readMap(JsonReader::getString)); - } else if ("managed".equals(fieldName)) { - properties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("release_policy".equals(fieldName)) { - properties.setReleasePolicy(KeyReleasePolicy.fromJson(reader)); - } else { - reader.skipChildren(); - } - } - - return new KeyVaultKey(webKey, properties); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifier.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifier.java deleted file mode 100644 index 06cc42d3cdec..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifier.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.keys.KeyAsyncClient; -import com.azure.security.keyvault.keys.KeyClient; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * Information about a {@link KeyVaultKey} parsed from the key URL. You can use this information when calling methods - * of {@link KeyClient} or {@link KeyAsyncClient}. - */ -@Immutable -public final class KeyVaultKeyIdentifier { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultKeyIdentifier.class); - - private final String sourceId; - private final String vaultUrl; - private final String name; - private final String version; - - /** - * Create a new {@link KeyVaultKeyIdentifier} from a given Key Vault identifier. - * - *

Some examples: - * - *

    - *
  • https://{key-vault-name}.vault.azure.net/keys/{key-name}
  • - *
  • https://{key-vault-name}.vault.azure.net/keys/{key-name}/pending
  • - *
  • https://{key-vault-name}.vault.azure.net/keys/{key-name}/{unique-version-id}
  • - *
  • https://{key-vault-name}.vault.azure.net/deletedkeys/{deleted-key-name}
  • - *
- * - * @param sourceId The identifier to extract information from. - * - * @throws IllegalArgumentException If {@code sourceId} is an invalid Key Vault identifier. - * @throws NullPointerException If {@code sourceId} is {@code null}. - */ - public KeyVaultKeyIdentifier(String sourceId) { - if (sourceId == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'sourceId' cannot be null.")); - } - - try { - final URL url = new URL(sourceId); - // We expect an sourceId with either 3 or 4 path segments: key vault + collection + name + "pending"/version - final String[] pathSegments = url.getPath().split("/"); - - // More or less segments in the URI than expected. - if (pathSegments.length != 3 && pathSegments.length != 4) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("'sourceId' is not a valid Key Vault identifier.")); - } - - this.sourceId = sourceId; - this.vaultUrl = url.getProtocol() + "://" + url.getHost(); - this.name = pathSegments[2]; - this.version = pathSegments.length == 4 ? pathSegments[3] : null; - } catch (MalformedURLException e) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("'sourceId' is not a valid Key Vault identifier.", e)); - } - } - - /** - * Gets the key identifier used to create this object. - * - * @return The key identifier. - */ - public String getSourceId() { - return sourceId; - } - - /** - * Gets the URL of the Key Vault. - * - * @return The Key Vault URL. - */ - public String getVaultUrl() { - return vaultUrl; - } - - /** - * Gets the name of the key. - * - * @return The key name. - */ - public String getName() { - return name; - } - - /** - * Gets the optional version of the key. - * - * @return The key version. - */ - public String getVersion() { - return version; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyOptions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyOptions.java deleted file mode 100644 index b28a188a1fcf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyOptions.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Fluent; - -/** - * Represents the configurable options to release a key. - */ -@Fluent -public final class ReleaseKeyOptions { - /* - * A client provided nonce for freshness. - */ - private String nonce; - - /* - * The encryption algorithm to use to protected the exported key material - */ - private KeyExportEncryptionAlgorithm algorithm; - - /** - * Creates a new instance of {@link ReleaseKeyOptions}. - */ - public ReleaseKeyOptions() { - } - - /** - * Get a client provided nonce for freshness. - * - * @return A client provided nonce for freshness. - */ - public String getNonce() { - return this.nonce; - } - - /** - * Set a client provided nonce for freshness. - * - * @param nonce A client provided nonce for freshness. - * - * @return The updated {@link ReleaseKeyOptions} object. - */ - public ReleaseKeyOptions setNonce(String nonce) { - this.nonce = nonce; - - return this; - } - - /** - * Get the encryption algorithm to use to protected the exported key material. - * - * @return The encryption algorithm to use to protected the exported key material. - */ - public KeyExportEncryptionAlgorithm getAlgorithm() { - return this.algorithm; - } - - /** - * Set the encryption algorithm to use to protected the exported key material. - * - * @param algorithm The encryption algorithm to use to protected the exported key material. - * - * @return The updated {@link ReleaseKeyOptions} object. - */ - public ReleaseKeyOptions setAlgorithm(KeyExportEncryptionAlgorithm algorithm) { - this.algorithm = algorithm; - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java deleted file mode 100644 index 738a6c76067e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.keys.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The release result, containing the released key. - */ -@Immutable -public final class ReleaseKeyResult implements JsonSerializable { - /* - * A signed object containing the released key. - */ - private String value; - - /** - * Creates an instance of ReleaseKeyResult class. - */ - public ReleaseKeyResult() { - } - - /** - * Get the value property: A signed object containing the released key. - * - * @return the value value. - */ - public String getValue() { - return this.value; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ReleaseKeyResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ReleaseKeyResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ReleaseKeyResult. - */ - public static ReleaseKeyResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ReleaseKeyResult deserializedReleaseKeyResult = new ReleaseKeyResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedReleaseKeyResult.value = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedReleaseKeyResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java deleted file mode 100644 index 63e0a5265402..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the data models for KeyClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. - */ -package com.azure.security.keyvault.keys.models; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java deleted file mode 100644 index 61944b9d9d3c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - *

Azure Key Vault is a cloud-based service - * provided by Microsoft Azure that allows users to securely store and manage cryptographic keys used for encrypting - * and decrypting data. It is a part of Azure Key Vault, which is a cloud-based service for managing cryptographic keys, - * secrets, and certificates.

- * - *

Azure Key Vault Keys provides a centralized and highly secure key management solution, allowing you to protect - * your keys and control access to them. It eliminates the need for storing keys in code or configuration files, - * reducing the risk of exposure and unauthorized access.

- * - *

With Azure Key Vault Keys, you can perform various operations on cryptographic keys, such as creating keys, - * importing existing keys, generating key pairs, encrypting data using keys, and decrypting data using keys. - * The service supports various key types and algorithms, including symmetric keys, asymmetric keys, and - * Elliptic Curve Cryptography (ECC) keys.

- * - *

The Azure Key Vault Keys client library allows developers to interact with the Azure Key Vault service - * from their applications. The library provides a set of APIs that enable developers to securely create keys, - * import existing keys, delete keys, retrieving key metadata, encrypting and decrypting data using keys, - * and signing and verifying signatures using keys.

- * - *

Key Concepts:

- * - *

What is a Key Client?

- *

The key client performs the interactions with the Azure Key Vault service for getting, setting, updating, - * deleting, and listing keys and its versions. Asynchronous (`KeyAsyncClient`) and synchronous (`KeyClient`) clients - * exist in the SDK allowing for the selection of a client based on an application's use case. Once you have - * initialized a key, you can interact with the primary resource types in Key Vault.

- * - *

What is an Azure Key Vault Key ?

- *

Azure Key Vault supports multiple key types (RSA and EC) and algorithms, and enables the use of - * Hardware Security Modules (HSM) for high value keys. In addition to the key material, the following attributes may - * be specified:

- * - *
    - *
  • enabled: Specifies whether the key is enabled and usable for cryptographic operations.
  • - *
  • notBefore: Identifies the time before which the key must not be used for cryptographic operations.
  • - *
  • expires: Identifies the expiration time on or after which the key MUST NOT be used for cryptographic operations.
  • - *
  • created: Indicates when this version of the key was created.
  • - *
  • updated: Indicates when this version of the key was updated.
  • - *
- * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link com.azure.security.keyvault.keys.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 {@link com.azure.security.keyvault.keys.KeyClient}, - * using the {@link com.azure.security.keyvault.keys.KeyClientBuilder} to configure it.

- * - * - *
- * KeyClient keyClient = new KeyClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *

Sample: Construct Asynchronous Key Client

- * - *

The following code sample demonstrates the creation of a - * {@link com.azure.security.keyvault.keys.KeyClient}, using the - * {@link com.azure.security.keyvault.keys.KeyClientBuilder} to configure it.

- * - * - *
- * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *
- * - *

Create a Cryptographic Key

- * The {@link com.azure.security.keyvault.keys.KeyClient} or - * {@link com.azure.security.keyvault.keys.KeyAsyncClient} can be used to create a key in the key vault. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously create a cryptographic key in the key vault, - * using the {@link com.azure.security.keyvault.keys.KeyClient#createKey(java.lang.String, com.azure.security.keyvault.keys.models.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 - * {@link com.azure.security.keyvault.keys.KeyAsyncClient}.

- * - *
- * - *
- * - *

Get a Cryptographic Key

- * The {@link com.azure.security.keyvault.keys.KeyClient} or - * {@link com.azure.security.keyvault.keys.KeyAsyncClient} can be used to retrieve a key from the - * key vault. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously retrieve a key from the key vault, using - * the {@link com.azure.security.keyvault.keys.KeyClient#getKey(java.lang.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 - * {@link com.azure.security.keyvault.keys.KeyAsyncClient}.

- * - *
- * - *
- * - *

Delete a Cryptographic Key

- * The {@link com.azure.security.keyvault.keys.KeyClient} or - * {@link com.azure.security.keyvault.keys.KeyAsyncClient} can be used to delete a key from the key vault. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously delete a key from the - * key vault, using the {@link com.azure.security.keyvault.keys.KeyClient#beginDeleteKey(java.lang.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 - * {@link com.azure.security.keyvault.keys.KeyAsyncClient}.

- * - * @see com.azure.security.keyvault.keys.KeyClient - * @see com.azure.security.keyvault.keys.KeyAsyncClient - * @see com.azure.security.keyvault.keys.KeyClientBuilder - */ -package com.azure.security.keyvault.keys; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java deleted file mode 100644 index 88148cf46e4a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -module com.azure.security.keyvault.keys { - requires transitive com.azure.core; - requires com.azure.json; - - requires java.xml.crypto; - - exports com.azure.security.keyvault.keys; - exports com.azure.security.keyvault.keys.cryptography; - exports com.azure.security.keyvault.keys.cryptography.models; - exports com.azure.security.keyvault.keys.models; - - opens com.azure.security.keyvault.keys to com.azure.core; - opens com.azure.security.keyvault.keys.cryptography to com.azure.core; - opens com.azure.security.keyvault.keys.cryptography.implementation to com.azure.core; - opens com.azure.security.keyvault.keys.cryptography.models to com.azure.core; - opens com.azure.security.keyvault.keys.implementation to com.azure.core; - opens com.azure.security.keyvault.keys.implementation.models to com.azure.core; - opens com.azure.security.keyvault.keys.models to com.azure.core; -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/proxy-config.json b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/proxy-config.json deleted file mode 100644 index 6692a55438b3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/proxy-config.json +++ /dev/null @@ -1,8 +0,0 @@ -[ - [ - "com.azure.security.keyvault.keys.implementation.KeyClientImpl$KeyClientService" - ], - [ - "com.azure.security.keyvault.keys.implementation.SecretMinClientImpl$SecretMinClientService" - ] -] diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/reflect-config.json b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/reflect-config.json deleted file mode 100644 index 9052acdf69ce..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/reflect-config.json +++ /dev/null @@ -1,746 +0,0 @@ -[ - { - "name": "com.azure.security.keyvault.keys.KeyAsyncClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.KeyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.KeyClientBuilder", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.KeyServiceVersion", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes128Cbc", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes128CbcHmacSha256", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes128CbcPad", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes128Kw", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes192Cbc", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes192CbcHmacSha384", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes192CbcPad", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes192Kw", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes256Cbc", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes256CbcHmacSha512", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes256CbcPad", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Aes256Kw", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AesCbc", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AesCbcHmacSha2", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AesCbcPad", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AesKeyCryptographyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AesKw", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Algorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AlgorithmResolver", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AsymmetricEncryptionAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.AsymmetricSignatureAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.ByteExtensions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.CryptographyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.CryptographyServiceClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.CryptographyServiceVersion", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.CryptoUtil", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Ecdsa", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.EcKeyCryptographyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Es256", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Es256k", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Es384", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Es512", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.HashAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.IAuthenticatedCryptoTransform", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.ICryptoTransform", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.ISignatureTransform", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.KeyEncryptionAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.KeyEncryptionKeyAsyncClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.KeyEncryptionKeyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.KeyEncryptionKeyClientBuilder", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.LocalEncryptionAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.LocalKeyCryptographyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.LocalKeyWrapAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.LocalSignatureAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Rsa15", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.RsaEncryption", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.RsaKeyCryptographyClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.RsaOaep", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.SignatureEncoding", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.SignatureHashResolver", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Strings", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.SymmetricEncryptionAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.Triplet", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.CryptographyService", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.KeyOperationParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.KeyOperationResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.KeySignRequest", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.KeyVerifyRequest", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.KeyVerifyResponse", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.KeyWrapUnwrapRequest", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.SecretKey", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.SecretProperties", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.SecretRequestAttributes", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.implementation.SecretRequestParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.DecryptParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.DecryptResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.EncryptParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.EncryptResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.SignResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.UnwrapResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.VerifyResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.cryptography.models.WrapResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.Base64UrlJsonDeserializer", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.Base64UrlJsonSerializer", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.BinaryDataJsonDeserializer", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.BinaryDataJsonSerializer", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.ByteExtensions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyBackup", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyClientImpl", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyImportRequestParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyReleaseParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyRequestAttributes", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyRequestParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyRestoreRequestParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.KeyVaultErrorCodeStrings", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.DeletedKeyPage", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.GetRandomBytesRequest", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.KeyPropertiesPage", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicyAttributes", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.LifetimeAction", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.LifetimeActionTrigger", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.LifetimeActionType", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.implementation.models.RandomBytes", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.CreateEcKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.CreateKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.CreateOctKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.CreateOkpKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.CreateRsaKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.DeletedKey", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.ImportKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.JsonWebKey", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyCurveName", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyOperation", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyProperties", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyReleasePolicy", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyRotationPolicy", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyRotationPolicyAction", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyType", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyVaultKey", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.KeyVaultKeyIdentifier", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.ReleaseKeyOptions", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.keys.models.ReleaseKeyResult", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - } -] \ No newline at end of file diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json deleted file mode 100644 index 0e369c703295..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "resources": { - "includes": [ - { - "pattern": "azure-key-vault-keys.properties" - }, - { - "pattern": "kvErrorStrings.properties" - } - ] - }, - "bundles": [] -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-key-vault-keys.properties b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-key-vault-keys.properties deleted file mode 100644 index ca812989b4f2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-key-vault-keys.properties +++ /dev/null @@ -1,2 +0,0 @@ -name=${project.artifactId} -version=${project.version} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md b/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md deleted file mode 100644 index bf5efc5803dd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -page_type: sample -languages: - - java -products: - - azure - - azure-key-vault -urlFragment: keyvault-keys-samples ---- -# Azure Key Vault Keys Samples client library for Java -This document explains samples and how to use them. - -## Key concepts -Key concepts are explained in detail [here][SDK_README_KEY_CONCEPTS]. - -## Getting started -Getting started explained in detail [here][SDK_README_GETTING_STARTED]. - -## Examples - Following section document various examples. - -### Hello World Samples -* [HelloWorld.java][sample_helloWorld] - and [HelloWorldAsync.java][sample_helloWorldAsync] - Contains samples for following scenarios: - * Create a Key - * Retrieve a Key - * Update a Key - * Delete a Key - -### List Operations Samples -* [ListOperations.java][sample_list] and [ListOperationsAsync.java][sample_listAsync] - Contains samples for following scenarios: - * Create a Key - * List Keys - * Create new version of existing key. - * List versions of an existing key. - -### Backup And Restore Operations Samples -* [BackupAndRestoreOperations.java][sample_BackupRestore] and [BackupAndRestoreOperationsAsync.java][sample_BackupRestoreAsync] - Contains samples for following scenarios: - * Create a Key - * Backup a Key -- Write it to a file. - * Delete a key - * Restore a key - -### Managing Deleted Keys Samples: -* [ManagingDeletedKeys.java][sample_ManageDeleted] and [ManagingDeletedKeysAsync.java][sample_ManageDeletedAsync] - Contains samples for following scenarios: - * Create a Key - * Delete a key - * List deleted keys - * Recover a deleted key - * Purge Deleted key - -### Encrypt And Decrypt Operations Samples: -* [EncryptAndDecryptOperations.java][sample_encryptDecrypt] and [EncryptAndDecryptOperationsAsync.java][sample_encryptDecryptAsync] - Contains samples for following scenarios: - * Encrypting plain text with asymmetric key - * Decrypting plain text with asymmetric key - * Encrypting plain text with symmetric key - * Decrypting plain text with symmetric key - -### Sign And Verify Operations Samples: -* [SignAndVerifyOperations.java][sample_signVerify] and [SignAndVerifyOperationsAsync.java][sample_signVerifyAsync] - Contains samples for following scenarios: - * Signing a digest - * Verifying signature against a digest - * Signing raw data content - * Verifyng signature against raw data content - -### Key Wrap And Unwrap Operations Samples: -* [KeyWrapUnwrapOperations.java][sample_wrapUnwrap] and [KeyWrapUnwrapOperationsAsync.java][sample_wrapUnwrapAsync] - Contains samples for following scenarios: - * Wrapping a key with asymmetric key - * Unwrapping a key with asymmetric key - * Wrapping a key with symmetric key - * Unwrapping a key with symmetric key - -## Troubleshooting -### General -Key Vault clients raise exceptions. For example, if you try to retrieve a key after it is deleted a `404` error is returned, indicating resource not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. -```java -try { - keyClient.getKey("deletedKey") -} catch (ResourceNotFoundException e) { - System.out.println(e.getMessage()); -} -``` - -## Next steps -Start using KeyVault Java SDK in your solutions. Our SDK details could be found at [SDK README][KEYS_SDK_README]. - -### Additional Documentation -For more extensive documentation on Azure Key Vault, see the [API reference documentation][azkeyvault_rest]. - -## Contributing -This project welcomes contributions and suggestions. Find [more contributing][SDK_README_CONTRIBUTING] details here. - - -[KEYS_SDK_README]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md -[SDK_README_CONTRIBUTING]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#contributing -[SDK_README_GETTING_STARTED]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#getting-started -[SDK_README_KEY_CONCEPTS]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#key-concepts -[azkeyvault_rest]: https://learn.microsoft.com/rest/api/keyvault/ -[sample_helloWorld]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java -[sample_helloWorldAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java -[sample_list]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java -[sample_listAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java -[sample_BackupRestore]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java -[sample_BackupRestoreAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java -[sample_ManageDeleted]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java -[sample_ManageDeletedAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java -[sample_encryptDecrypt]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperations.java -[sample_encryptDecryptAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperationsAsync.java -[sample_signVerify]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperations.java -[sample_signVerifyAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperationsAsync.java -[sample_wrapUnwrap]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperations.java -[sample_wrapUnwrapAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperationsAsync.java - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-keys%2Fsrc%2Fsamples%2FREADME.png) diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java deleted file mode 100644 index e389f7730b60..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to backup and restore keys in the key vault. - */ -public class BackupAndRestoreOperations { - /** - * Authenticates with the key vault and shows how to backup and restore keys in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - * @throws IOException when writing backup to file is unsuccessful. - */ - public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { - /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure - credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of - // the key is created. - keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)); - - // Backups are good to have, if in case keys get accidentally deleted by you. - // For long term storage, it is ideal to write the backup to a file. - String backupFilePath = "YOUR_BACKUP_FILE_PATH"; - byte[] keyBackup = keyClient.backupKey("CloudRsaKey"); - - writeBackupToFile(keyBackup, backupFilePath); - - // The RSA key is no longer in use, so you delete it. - SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); - PollResponse pollResponse = rsaDeletedKeyPoller.poll(); - DeletedKey rsaDeletedKey = pollResponse.getValue(); - - System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); - System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); - - // The key is being deleted on the server. - rsaDeletedKeyPoller.waitForCompletion(); - - // To ensure the key is deleted server-side. - Thread.sleep(30000); - - // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. - keyClient.purgeDeletedKey("CloudRsaKey"); - - // To ensure the key is purged server-side. - Thread.sleep(15000); - - // After sometime, the key is required again. We can use the backup value to restore it in the key vault. - byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); - KeyVaultKey restoredKey = keyClient.restoreKeyBackup(backupFromFile); - } - - private static void writeBackupToFile(byte[] bytes, String filePath) { - try { - File file = new File(filePath); - - if (file.exists()) { - file.delete(); - } - - file.createNewFile(); - - OutputStream os = new FileOutputStream(file); - os.write(bytes); - - System.out.println("Successfully wrote backup to file."); - - // Close the file - os.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java deleted file mode 100644 index d888fb65e64c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously backup and restore keys in the key vault. - */ -public class BackupAndRestoreOperationsAsync { - /** - * Authenticates with the key vault and shows how to asynchronously backup and restore keys in the key vault. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - * @throws IOException when writing backup to file is unsuccessful. - */ - public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { - /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create RSA key valid for 1 year. If the key - // already exists in the key vault, then a new version of the key is created. - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), keyResponse.getKeyType())); - - Thread.sleep(2000); - - // Backups are good to have, if in case keys get accidentally deleted by you. - // For long term storage, it is ideal to write the backup to a file. - String backupFilePath = "YOUR_BACKUP_FILE_PATH"; - keyAsyncClient.backupKey("CloudRsaKey").subscribe(backupResponse -> { - byte[] backupBytes = backupResponse; - writeBackupToFile(backupBytes, backupFilePath); - }); - - Thread.sleep(7000); - - // The RSA key is no longer in use, so you delete it. - keyAsyncClient.beginDeleteKey("CloudRsaKey") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); - System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); - }); - - // To ensure file is deleted server-side. - Thread.sleep(30000); - - // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. - keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse -> - System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); - - // To ensure file is purged server-side. - Thread.sleep(15000); - - // After sometime, the key is required again. We can use the backup value to restore it in the key vault. - byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); - keyAsyncClient.restoreKeyBackup(backupFromFile).subscribe(keyResponse -> - System.out.printf("Restored Key with name %s %n", keyResponse.getName())); - - // To ensure the key is restored server-side. - Thread.sleep(15000); - } - - private static void writeBackupToFile(byte[] bytes, String filePath) { - try { - File file = new File(filePath); - if (file.exists()) { - file.delete(); - } - file.createNewFile(); - OutputStream os = new FileOutputStream(file); - os.write(bytes); - System.out.println("Successfully wrote backup to file."); - // Close the file - os.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java deleted file mode 100644 index 6825c8560a51..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import com.azure.identity.DefaultAzureCredentialBuilder; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to set, get, update and delete a key. - */ -public class HelloWorld { - /** - * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException, IllegalArgumentException { - /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure - credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of - // the key is created. - Response createKeyResponse = - keyClient.createRsaKeyWithResponse(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048), new Context("key1", "value1")); - - // Let's validate the create key operation succeeded using the status code information in the response. - System.out.printf("Create Key operation succeeded with status code %s \n", createKeyResponse.getStatusCode()); - - // Let's get the RSA key from the key vault. - KeyVaultKey cloudRsaKey = keyClient.getKey("CloudRsaKey"); - - System.out.printf("Key is returned with name %s and type %s \n", cloudRsaKey.getName(), - cloudRsaKey.getKeyType()); - - // After one year, the RSA key is still required, we need to update the expiry time of the key. - // The update method can be used to update the expiry attribute of the key. - cloudRsaKey.getProperties().setExpiresOn(cloudRsaKey.getProperties().getExpiresOn().plusYears(1)); - - KeyVaultKey updatedKey = keyClient.updateKeyProperties(cloudRsaKey.getProperties()); - - System.out.printf("Key's updated expiry time %s \n", updatedKey.getProperties().getExpiresOn()); - - // We need the RSA key with bigger key size, so you want to update the key in key vault to ensure it has the - // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault - // with the new specified size. - keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(4096)); - - // The RSA key is no longer needed, need to delete it from the key vault. - SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); - PollResponse pollResponse = rsaDeletedKeyPoller.poll(); - DeletedKey rsaDeletedKey = pollResponse.getValue(); - - System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); - System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); - - // The key is being deleted on the server. - rsaDeletedKeyPoller.waitForCompletion(); - - // To ensure the key is deleted server-side. - Thread.sleep(30000); - - // If the keyvault is soft-delete enabled, then deleted keys need to be purged for permanent deletion. - keyClient.purgeDeletedKey("CloudRsaKey"); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java deleted file mode 100644 index 0ab8b4d4da48..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.http.rest.Response; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import com.azure.identity.DefaultAzureCredentialBuilder; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously set, get, update and delete a key. - */ -public class HelloWorldAsync { - /** - * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key - * vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException { - /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of - // the key is created. - Response createKeyResponse = keyAsyncClient.createRsaKeyWithResponse(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)).block(); - - // Let's validate create key operation succeeded using the status code information in the response. - System.out.printf("Create Key operation succeeded with status code %s%n", createKeyResponse.getStatusCode()); - System.out.printf("Key is created with name %s and type %s%n", createKeyResponse.getValue().getName(), - createKeyResponse.getValue().getKeyType()); - - Thread.sleep(2000); - - // Let's get the RSA key from the key vault. - keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> - System.out.printf("Key returned with name %s and type %s%n", keyResponse.getName(), keyResponse.getKeyType())); - - Thread.sleep(2000); - - // After one year, the RSA key is still required, we need to update the expiry time of the key. - // The update method can be used to update the expiry attribute of the key. - keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> { - KeyVaultKey key = keyResponse; - - // Update the expiry time of the key. - key.getProperties().setExpiresOn(key.getProperties().getExpiresOn().plusYears(1)); - keyAsyncClient.updateKeyProperties(key.getProperties()) - .subscribe(updatedKeyResponse -> - System.out.printf("Key's updated expiry time %s%n", - updatedKeyResponse.getProperties().getExpiresOn().toString())); - }); - - Thread.sleep(2000); - - // We need the RSA key with bigger key size, so you want to update the key in key vault to ensure it has the - // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault - // with the new specified size. - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(4096)) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s%n", keyResponse.getName(), - keyResponse.getKeyType())); - - Thread.sleep(2000); - - // The RSA key is no longer needed, need to delete it from the key vault. - keyAsyncClient.beginDeleteKey("CloudRsaKey") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); - System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); - }); - - // To ensure the key is deleted server-side. - Thread.sleep(30000); - - // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. - keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey") - .subscribe(purgeResponse -> - System.out.printf("RSA key purge status response %d%n", purgeResponse.getStatusCode())); - - // To ensure the key is purged server-side. - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyAsyncClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyAsyncClientJavaDocCodeSnippets.java deleted file mode 100644 index 0290622d5ac7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyAsyncClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,640 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; -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.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.KeyRotationLifetimeAction; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -import com.azure.security.keyvault.keys.models.KeyType; -import com.azure.security.keyvault.keys.models.ReleaseKeyOptions; -import reactor.util.context.Context; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyAsyncClient}. - */ -public final class KeyAsyncClientJavaDocCodeSnippets { - /** - * Generates code sample for creating a {@link KeyAsyncClient}. - * - * @return An instance of {@link KeyAsyncClient}. - */ - public KeyAsyncClient createAsyncClient() { - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation - return keyAsyncClient; - } - - /** - * Generates code sample for creating a {@link KeyAsyncClient} using a custom {@link HttpClient}. - * - * @return An instance of {@link KeyAsyncClient}. - */ - public KeyAsyncClient createAsyncClientWithHttpClient() { - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .httpClient(HttpClient.createDefault()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient - return keyAsyncClient; - } - - /** - * Generates code samples for using {@link KeyAsyncClient#createKey(String, KeyType)}, - * {@link KeyAsyncClient#createKey(CreateKeyOptions)}, - * {@link KeyAsyncClient#createRsaKey(CreateRsaKeyOptions)}, - * {@link KeyAsyncClient#createEcKey(CreateEcKeyOptions)} and - * {@link KeyAsyncClient#createOctKey(CreateOctKeyOptions)}. - */ - public void createKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions - } - - /** - * Generates code samples for using {@link KeyAsyncClient#importKey(String, JsonWebKey)}, - * {@link KeyAsyncClient#importKey(ImportKeyOptions)} and - * {@link KeyAsyncClient#importKeyWithResponse(ImportKeyOptions)}. - */ - public void importKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - JsonWebKey jsonWebKeyToImport = new JsonWebKey(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey - keyAsyncClient.importKey("keyName", jsonWebKeyToImport) - .subscribe(keyVaultKey -> - System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), - keyVaultKey.getId())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#beginDeleteKey(String)}. - */ - public void beginDeleteKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String - 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()); - }); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#getDeletedKey(String)}. - */ - public void getDeletedKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String - keyAsyncClient.getDeletedKey("keyName") - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(deletedKey -> - System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#createKeyWithResponse(CreateKeyOptions)}, - * {@link KeyAsyncClient#createRsaKeyWithResponse(CreateRsaKeyOptions)}, - * {@link KeyAsyncClient#createEcKeyWithResponse(CreateEcKeyOptions)} and - * {@link KeyAsyncClient#createOctKeyWithResponse(CreateOctKeyOptions)}. - */ - public void createKeyWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#getKeyWithResponse(String, String)}. - */ - public void getKeyWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#getKey(String, String)}. - */ - public void getKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String - } - - /** - * Generates a code sample for using - * {@link KeyAsyncClient#updateKeyPropertiesWithResponse(KeyProperties, KeyOperation...)}. - */ - public void updateKeyPropertiesWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation - 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())); - }); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#updateKeyProperties(KeyProperties, KeyOperation...)}. - */ - public void updateKeyProperties() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation - 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())); - }); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#getDeletedKeyWithResponse(String)}. - */ - public void getDeletedKeyWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#purgeDeletedKey(String)}. - */ - public void purgeDeletedKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String - keyAsyncClient.purgeDeletedKey("deletedKeyName") - .subscribe(ignored -> - System.out.println("Successfully purged deleted key")); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#purgeDeletedKeyWithResponse(String)}. - */ - public void purgeDeletedKeyWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String - keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName") - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(purgeDeletedKeyResponse -> - System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#beginRecoverDeletedKey(String)}. - */ - public void beginRecoverDeletedKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String - 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()); - }); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#backupKey(String)}. - */ - public void backupKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String - keyAsyncClient.backupKey("keyName") - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(bytes -> - System.out.printf("Key backup byte array length: %s%n", bytes.length)); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#backupKeyWithResponse(String)}. - */ - public void backupKeyWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String - 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)); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#restoreKeyBackup}. - */ - public void restoreKeyBackup() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - byte[] keyBackupByteArray = {}; - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#restoreKeyBackupWithResponse(byte[])}. - */ - public void restoreKeyBackupWithResponse() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - byte[] keyBackupByteArray = {}; - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#listPropertiesOfKeys}. - */ - public void listPropertiesOfKeys() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys - } - - /** - * Generates a code sample for using {@link KeyAsyncClient#listDeletedKeys()}. - */ - public void listDeletedKeys() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys - keyAsyncClient.listDeletedKeys() - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(deletedKey -> - System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys - } - - /** - * Generates code sample for using {@link KeyAsyncClient#listPropertiesOfKeyVersions(String)}. - */ - public void listPropertiesOfKeyVersions() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions - } - - /** - * Generates code samples for using {@link KeyAsyncClient#getRandomBytes(int)} and - * {@link KeyAsyncClient#getRandomBytesWithResponse(int)}. - */ - public void getRandomBytes() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int - int amount = 16; - keyAsyncClient.getRandomBytes(amount) - .subscribe(randomBytes -> - System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes))); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int - 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()))); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int - } - - /** - * Generates code samples for using {@link KeyAsyncClient#releaseKey(String, String)}, - * {@link KeyAsyncClient#releaseKey(String, String, String)} and - * {@link KeyAsyncClient#releaseKeyWithResponse(String, String, String, ReleaseKeyOptions)}. - */ - public void releaseKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String - String targetAttestationToken = "someAttestationToken"; - - keyAsyncClient.releaseKey("keyName", targetAttestationToken) - .subscribe(releaseKeyResult -> - System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions - } - - /** - * Generates code samples for using {@link KeyAsyncClient#rotateKey(String)} and - * {@link KeyAsyncClient#rotateKeyWithResponse(String)}. - */ - public void rotateKey() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String - keyAsyncClient.rotateKey("keyName") - .subscribe(key -> - System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), - key.getProperties().getVersion())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String - } - - /** - * Generates code samples for using {@link KeyAsyncClient#getKeyRotationPolicy(String)} and - * {@link KeyAsyncClient#getKeyRotationPolicyWithResponse(String)}. - */ - public void getKeyRotationPolicy() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String - keyAsyncClient.getKeyRotationPolicy("keyName") - .subscribe(keyRotationPolicy -> - System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String - 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String - } - - /** - * Generates code samples for using - * {@link KeyAsyncClient#updateKeyRotationPolicy(String, KeyRotationPolicy)} and - * {@link KeyAsyncClient#updateKeyRotationPolicyWithResponse(String, KeyRotationPolicy)}. - */ - public void updateKeyRotationPolicy() { - KeyAsyncClient keyAsyncClient = createAsyncClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicy - List 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicy - - // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy - List 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())); - // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyClientJavaDocCodeSnippets.java deleted file mode 100644 index b97130754501..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,662 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -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.KeyRotationLifetimeAction; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -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 java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyClient}. - */ -public final class KeyClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyClient}. - * - * @return An instance of {@link KeyClient}. - */ - public KeyClient createClient() { - // BEGIN: com.azure.security.keyvault.keys.KeyClient.instantiation - KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: com.azure.security.keyvault.keys.KeyClient.instantiation - return keyClient; - } - - /** - * Generates a code sample for using {@link KeyClient#createKey(String, KeyType)}, - * {@link KeyClient#createRsaKey(CreateRsaKeyOptions)}, - * {@link KeyClient#createEcKey(CreateEcKeyOptions)} and - * {@link KeyClient#createOctKey(CreateOctKeyOptions)}. - */ - public void createKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType - KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC); - System.out.printf("Created key with name: %s and id: %s%n", key.getName(), key.getId()); - // END: com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions - 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions - 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions - 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions - 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions - } - - /** - * Generates code samples for using {@link KeyAsyncClient#importKey(String, JsonWebKey)}, - * {@link KeyAsyncClient#importKey(ImportKeyOptions)} and - * {@link KeyAsyncClient#importKeyWithResponse(ImportKeyOptions)}. - */ - public void importKey() { - KeyClient keyClient = createClient(); - JsonWebKey jsonWebKeyToImport = new JsonWebKey(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey - KeyVaultKey key = keyClient.importKey("keyName", jsonWebKeyToImport); - - System.out.printf("Imported key with name: %s and id: %s%n", key.getName(), key.getId()); - // END: com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions - 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()); - // END: com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context - ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport) - .setHardwareProtected(false); - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context - } - - /** - * Generates a code sample for using {@link KeyClient#beginDeleteKey(String)}. - */ - public void beginDeleteKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.deleteKey#String - SyncPoller deleteKeyPoller = keyClient.beginDeleteKey("keyName"); - PollResponse 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 - // END: com.azure.security.keyvault.keys.KeyClient.deleteKey#String - } - - /** - * Generates a code sample for using {@link KeyClient#getDeletedKey(String)}. - */ - public void getDeletedKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String - DeletedKey deletedKey = keyClient.getDeletedKey("keyName"); - - System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId()); - // END: com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String - } - - /** - * Generates a code sample for using {@link KeyClient#createKeyWithResponse(CreateKeyOptions, Context)}, - * {@link KeyClient#createRsaKeyWithResponse(CreateRsaKeyOptions, Context)}, - * {@link KeyClient#createEcKeyWithResponse(CreateEcKeyOptions, Context)} and - * {@link KeyClient#createOctKeyWithResponse(CreateOctKeyOptions, Context)}. - */ - public void createKeyWithResponse() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context - CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) - .setNotBefore(OffsetDateTime.now().plusDays(1)) - .setExpiresOn(OffsetDateTime.now().plusYears(1)); - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context - CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") - .setKeySize(2048) - .setNotBefore(OffsetDateTime.now().plusDays(1)) - .setExpiresOn(OffsetDateTime.now().plusYears(1)); - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context - CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") - .setCurveName(KeyCurveName.P_384) - .setNotBefore(OffsetDateTime.now().plusDays(1)) - .setExpiresOn(OffsetDateTime.now().plusYears(1)); - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions-Context - CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") - .setNotBefore(OffsetDateTime.now().plusDays(1)) - .setExpiresOn(OffsetDateTime.now().plusYears(1)); - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions-Context - } - - /** - * Generates a code sample for using {@link KeyClient#getKeyWithResponse(String, String, Context)}. - */ - public void getKeyWithResponse() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context - String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context - } - - /** - * Generates a code sample for using {@link KeyClient#getKey(String)} and - * {@link KeyClient#getKey(String, String)}. - */ - public void getKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKey#String - KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName"); - - System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(), - keyWithVersionValue.getId()); - // END: com.azure.security.keyvault.keys.KeyClient.getKey#String - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKey#String-String - String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; - KeyVaultKey keyWithVersion = keyClient.getKey("keyName", keyVersion); - - System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersion.getName(), - keyWithVersion.getId()); - // END: com.azure.security.keyvault.keys.KeyClient.getKey#String-String - } - - /** - * Generates a code sample for using - * {@link KeyClient#updateKeyPropertiesWithResponse(KeyProperties, Context, KeyOperation...)}. - */ - public void updateKeyPropertiesWithResponse() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation - KeyVaultKey key = keyClient.getKey("keyName"); - - key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); - - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation - } - - /** - * Generates a code sample for using {@link KeyClient#updateKeyProperties(KeyProperties, KeyOperation...)}. - */ - public void updateKeyProperties() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation - 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()); - // END: com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation - } - - /** - * Generates a code sample for using {@link KeyClient#getDeletedKeyWithResponse(String, Context)}. - */ - public void getDeletedKeyWithResponse() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context - Response deletedKeyResponse = - keyClient.getDeletedKeyWithResponse("keyName", new Context("key1", "value1")); - - System.out.printf("Deleted key with recovery id: %s%n", deletedKeyResponse.getValue().getRecoveryId()); - // END: com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context - } - - /** - * Generates a code sample for using {@link KeyClient#purgeDeletedKey(String)}. - */ - public void purgeDeletedKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String - keyClient.purgeDeletedKey("deletedKeyName"); - // END: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String - } - - /** - * Generates a code sample for using {@link KeyClient#purgeDeletedKeyWithResponse(String, Context)}. - */ - public void purgeDeletedKeyWithResponse() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context - Response purgeDeletedKeyResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName", - new Context("key1", "value1")); - - System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode()); - // END: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context - } - - /** - * Generates a code sample for using {@link KeyClient#beginRecoverDeletedKey(String)}. - */ - public void beginRecoverDeletedKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String - SyncPoller recoverKeyPoller = keyClient.beginRecoverDeletedKey("deletedKeyName"); - - PollResponse 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 - // END: com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String - } - - /** - * Generates a code sample for using {@link KeyClient#backupKey(String)}. - */ - public void backupKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.backupKey#String - byte[] keyBackup = keyClient.backupKey("keyName"); - - System.out.printf("Key backup byte array length: %s%n", keyBackup.length); - // END: com.azure.security.keyvault.keys.KeyClient.backupKey#String - } - - /** - * Generates a code sample for using {@link KeyClient#backupKeyWithResponse(String, Context)}. - */ - public void backupKeyWithResponse() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context - Response backupKeyResponse = keyClient.backupKeyWithResponse("keyName", new Context("key1", "value1")); - - System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length); - // END: com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context - } - - /** - * Generates a code sample for using {@link KeyClient#restoreKeyBackup}. - */ - public void restoreKeyBackup() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte - byte[] keyBackupByteArray = {}; - KeyVaultKey keyResponse = keyClient.restoreKeyBackup(keyBackupByteArray); - System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getName(), keyResponse.getId()); - // END: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte - } - - /** - * Generates a code sample for using {@link KeyClient#restoreKeyBackupWithResponse(byte[], Context)}. - */ - public void restoreKeyBackupWithResponse() { - KeyClient keyClient = createClient(); - byte[] keyBackupByteArray = {}; - // BEGIN: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context - } - - /** - * Generates a code sample for using {@link KeyClient#listPropertiesOfKeys()} and - * {@link KeyClient#listPropertiesOfKeys(Context)}. - */ - public void listPropertiesOfKeys() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys - 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()); - } - // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context - 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()); - } - // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage - 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()); - }); - }); - // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage - } - - /** - * Generates a code sample for using {@link KeyClient#listDeletedKeys()} and - * {@link KeyClient#listDeletedKeys(Context)}. - */ - public void listDeletedKeys() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys - for (DeletedKey deletedKey : keyClient.listDeletedKeys()) { - System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); - } - // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context - for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context("key1", "value1"))) { - System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); - } - // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage - 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())); - }); - // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage - } - - /** - * Generates code sample for using {@link KeyClient#listPropertiesOfKeyVersions(String)} and - * {@link KeyClient#listPropertiesOfKeyVersions(String, Context)}. - */ - public void listPropertiesOfKeyVersions() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String - 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()); - } - // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context - 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()); - } - // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage - 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())); - }); - // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage - } - - /** - * Generates code samples for using {@link KeyClient#getRandomBytes(int)} and - * {@link KeyClient#getRandomBytesWithResponse(int, Context)}. - */ - public void getRandomBytes() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int - int amount = 16; - byte[] randomBytes = keyClient.getRandomBytes(amount); - - System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes)); - // END: com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context - int amountOfBytes = 16; - Response 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())); - // END: com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context - } - - /** - * Generates code samples for using {@link KeyClient#releaseKey(String, String)}, - * {@link KeyClient#releaseKey(String, String, String)} and - * {@link KeyClient#releaseKeyWithResponse(String, String, String, ReleaseKeyOptions, Context)}. - */ - public void releaseKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String - String targetAttestationToken = "someAttestationToken"; - ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", targetAttestationToken); - - System.out.printf("Signed object containing released key: %s%n", releaseKeyResult); - // END: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String - String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; - String myTargetAttestationToken = "someAttestationToken"; - ReleaseKeyResult releaseKeyVersionResult = - keyClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken); - - System.out.printf("Signed object containing released key: %s%n", releaseKeyVersionResult); - // END: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context - String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; - String someTargetAttestationToken = "someAttestationToken"; - ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions() - .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256) - .setNonce("someNonce"); - - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context - } - - /** - * Generates code samples for using {@link KeyClient#rotateKey(String)} and - * {@link KeyClient#rotateKeyWithResponse(String, Context)}. - */ - public void rotateKey() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String - KeyVaultKey key = keyClient.rotateKey("keyName"); - - System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), - key.getProperties().getVersion()); - // END: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context - } - - /** - * Generates code samples for using {@link KeyClient#getKeyRotationPolicy(String)} and - * {@link KeyClient#getKeyRotationPolicyWithResponse(String, Context)}. - */ - public void getKeyRotationPolicy() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String - KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy("keyName"); - - System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId()); - // END: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context - Response 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()); - // END: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context - } - - /** - * Generates code samples for using {@link KeyClient#updateKeyRotationPolicy(String, KeyRotationPolicy)} - * and {@link KeyClient#updateKeyRotationPolicyWithResponse(String, KeyRotationPolicy, Context)}. - */ - public void updateKeyRotationPolicy() { - KeyClient keyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicy - List 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()); - // END: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicy - - // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy-Context - List 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 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()); - // END: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy-Context - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotation.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotation.java deleted file mode 100644 index 8717c3941233..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotation.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -import com.azure.security.keyvault.keys.models.KeyVaultKey; - -import java.util.ArrayList; -import java.util.List; - -/* - * This sample demonstrates how to set key rotation policies and manually rotate keys in Key Vault to create a new key - * version. - */ -public class KeyRotation { - /** - * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to - * create a new key version. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when an invalid key vault endpoint is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure - credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create an RSA key. - String keyName = "MyKey"; - KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); - - System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); - - // You can configure its key rotation policy to allow Azure Key Vault to do it automatically under certain - // conditions. Properties such as timeAfterCreate and timeBeforeExpiry should be defined as an ISO 8601 - // duration. For example, 90 days would be "P90D", 3 months would be "P3M" and 1 year and 10 days would be - // "P1Y10D". See https://wikipedia.org/wiki/ISO_8601#Durations for more information. - List keyRotationLifetimeActionList = new ArrayList<>(); - KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) - .setTimeAfterCreate("P90D"); // Rotate the key after 90 days of its creation. - - keyRotationLifetimeActionList.add(rotateLifetimeAction); - - KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() - .setLifetimeActions(keyRotationLifetimeActionList) - .setExpiresIn("P6M"); // Make any new versions of the key expire 6 months after creation. - - // An object containing the details of the recently updated key rotation policy will be returned by the update - // method. - KeyRotationPolicy updatedPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicy); - - System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId()); - - // You can also manually rotate a key by calling the following method. - KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); - - System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotationAsync.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotationAsync.java deleted file mode 100644 index c3458ea0b5ba..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/KeyRotationAsync.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; - -import java.util.ArrayList; -import java.util.List; - -/* - * This sample demonstrates how to set key rotation policies and manually rotate keys in Key Vault to create a new key - * version. - */ -public class KeyRotationAsync { - /** - * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to - * create a new key version. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when an invalid key vault endpoint is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create an RSA key. - String keyName = "MyKey"; - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)) - .subscribe(originalKey -> - System.out.printf("Key created with name: %s, and type: %s%n", originalKey.getName(), - originalKey.getKeyType())); - - // You can configure its key rotation policy to allow Azure Key Vault to do it automatically under certain - // conditions. Properties such as timeAfterCreate and timeBeforeExpiry should be defined as an ISO 8601 - // duration. For example, 90 days would be "P90D", 3 months would be "P3M" and 1 year and 10 days would be - // "P1Y10D". See https://wikipedia.org/wiki/ISO_8601#Durations for more information. - List keyRotationLifetimeActionList = new ArrayList<>(); - KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) - .setTimeAfterCreate("P90D"); // Rotate the key after 90 days of its creation. - - keyRotationLifetimeActionList.add(rotateLifetimeAction); - - KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() - .setLifetimeActions(keyRotationLifetimeActionList) - .setExpiresIn("P6M"); // Make any new versions of the key expire 6 months after creation. - - // An object containing the details of the recently updated key rotation policy will be returned by the update - // method. - keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) - .subscribe(updatedPolicy -> - System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId())); - - // You can also manually rotate a key by calling the following method. - keyAsyncClient.rotateKey(keyName) - .subscribe(manuallyRotatedKey -> - System.out.printf("Rotated key with name: %s%n", manuallyRotatedKey.getName())); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java deleted file mode 100644 index 3ae26850cb2b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.models.KeyProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to list keys and versions of a given key in the key vault. - */ -public class ListOperations { - /** - * Authenticates with the key vault and shows how to list keys and list versions of a specific key in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - */ - public static void main(String[] args) throws IllegalArgumentException { - /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure - credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create EC and ESA keys valid for 1 year. If a key already exists in the key vault, then a new version - // of the key is created. - keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)); - - keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))); - - // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. - // List operations don't return the keys with key material information. So, for each returned key we call - // getKey() to get the key with its key material information. - for (KeyProperties key : keyClient.listPropertiesOfKeys()) { - KeyVaultKey keyWithMaterial = keyClient.getKey(key.getName(), key.getVersion()); - - System.out.printf("Received key with name %s and type %s", keyWithMaterial.getName(), - keyWithMaterial.getKeyType()); - } - - // We need the RSA key with a bigger key size, so you want to update the key in key vault to ensure it has the - // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault - // with the new specified size. - keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(4096)); - - // You need to check all the different versions RSA key had previously. Lets print all the versions of this key. - for (KeyProperties key : keyClient.listPropertiesOfKeyVersions("CloudRsaKey")) { - KeyVaultKey keyWithMaterial = keyClient.getKey(key.getName(), key.getVersion()); - - System.out.printf("Received key's version with name %s, type %s and verison %s", keyWithMaterial.getName(), - keyWithMaterial.getKeyType(), keyWithMaterial.getProperties().getVersion()); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java deleted file mode 100644 index 76fef8f8a684..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously list keys and versions of a given key in the key vault. - */ -public class ListOperationsAsync { - /** - * Authenticates with the key vault and shows how to asynchronously list keys and list versions of a specific key in - * the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException { - /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create EC and RSA keys valid for 1 year. If a key already exists in the key vault, then a new version - // of the key is created. - keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), - keyResponse.getKeyType())); - - Thread.sleep(2000); - - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), - keyResponse.getKeyType())); - - Thread.sleep(2000); - - // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. - // List operations don't return the keys with key material information. So, for each returned key we call - // getKey() to get the key with its key material information. - keyAsyncClient.listPropertiesOfKeys() - .subscribe(keyBase -> - keyAsyncClient.getKey(keyBase.getName(), keyBase.getVersion()) - .subscribe(keyResponse -> - System.out.printf("Received key with name %s and type %s \n", keyResponse.getName(), - keyResponse.getKeyType()))); - - Thread.sleep(15000); - - // We need the RSA key with a bigger key size, so you want to update the key in key vault to ensure it has the - // required size. Calling createRsaKey on an existing key creates a new version of the key in the key vault - // with the new specified size. - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setKeySize(4096) - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), - keyResponse.getKeyType())); - - Thread.sleep(2000); - - // You need to check all the different versions RSA key had previously. Lets print all the versions of this key. - keyAsyncClient.listPropertiesOfKeyVersions("CloudRsaKey") - .subscribe(keyBase -> - keyAsyncClient.getKey(keyBase.getName(), keyBase.getVersion()) - .subscribe(keyResponse -> - System.out.printf("Received key's version with name %s, type %s and version %s \n", - keyResponse.getName(), keyResponse.getKeyType(), - keyResponse.getProperties().getVersion()))); - - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java deleted file mode 100644 index 21c4bdbf5366..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyVaultKey; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to list, recover and purge deleted keys in a soft-delete enabled key vault. - */ -public class ManagingDeletedKeys { - /** - * Authenticates with the key vault and shows how to list, recover and purge deleted keys in a soft-delete enabled - * key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws IllegalArgumentException, InterruptedException { - /* NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted - keys to be retained for a given retention period (90 days). During this period deleted keys can be recovered - and if a key needs to be permanently deleted then it needs to be purged.*/ - - /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure - credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create EC and RSA keys valid for 1 year. If the key already exists in the key vault, then a new version - // of the key is created. - keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)); - - keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))); - - // The RSA key is no longer needed, need to delete it from the key vault. - SyncPoller deletedKeyPoller = keyClient.beginDeleteKey("CloudEcKey"); - PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); - DeletedKey deletedKey = deletedKeyPollResponse.getValue(); - - System.out.println("Deleted Date %s" + deletedKey.getDeletedOn().toString()); - System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId()); - - // The key is being deleted on the server. - deletedKeyPoller.waitForCompletion(); - - // We accidentally deleted the EC key. Let's recover it. - // A deleted key can only be recovered if the key vault is soft-delete enabled. - SyncPoller recoverEcKeyPoller = keyClient.beginRecoverDeletedKey("CloudEcKey"); - PollResponse recoveryEcKeyPollResponse = recoverEcKeyPoller.poll(); - KeyVaultKey recoveredKey = recoveryEcKeyPollResponse.getValue(); - - System.out.println("Recovered Key Name %s" + recoveredKey.getName()); - System.out.printf("Recovered Key's Id %s", recoveredKey.getId()); - - // The key is being recovered on the server. - recoverEcKeyPoller.waitForCompletion(); - - // The EC and RSA keys are no longer needed, need to delete them from the key vault. - SyncPoller ecDeletedKeyPoller = keyClient.beginDeleteKey("CloudEcKey"); - PollResponse ecDeletedKeyPollResponse = ecDeletedKeyPoller.poll(); - DeletedKey ecDeletedKey = ecDeletedKeyPollResponse.getValue(); - - System.out.println("Deleted Date %s" + ecDeletedKey.getDeletedOn().toString()); - System.out.printf("Deleted Key's Recovery Id %s", ecDeletedKey.getRecoveryId()); - - // The key is being deleted on the server. - ecDeletedKeyPoller.waitForCompletion(); - - SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); - PollResponse rsaDeletedKeyPollResponse = rsaDeletedKeyPoller.poll(); - DeletedKey rsaDeletedKey = rsaDeletedKeyPollResponse.getValue(); - - System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); - System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); - - // The key is being deleted on the server. - rsaDeletedKeyPoller.waitForCompletion(); - - // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled. - for (DeletedKey delKey : keyClient.listDeletedKeys()) { - System.out.printf("Deleted key's recovery Id %s", delKey.getRecoveryId()); - } - - // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. - keyClient.purgeDeletedKey("CloudEcKey"); - keyClient.purgeDeletedKey("CloudRsaKey"); - - // To ensure the key is purged server-side. - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java deleted file mode 100644 index 1d8f5e136117..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault. - */ -public class ManagingDeletedKeysAsync { - /** - * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a - * soft-delete enabled key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException { - /* NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted - keys to be retained for a given retention period (90 days). During this period deleted keys can be recovered - and if a key needs to be permanently deleted then it needs to be purged.*/ - - /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create EC and RSA keys valid for 1 year. If the key already exists in the key vault, then a new version - // of the key is created. - keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), - keyResponse.getKeyType())); - - Thread.sleep(2000); - - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(keyResponse -> - System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), - keyResponse.getKeyType())); - - Thread.sleep(2000); - - // The RSA key is no longer needed, need to delete it from the key vault. - keyAsyncClient.beginDeleteKey("CloudEcKey") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); - System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); - }); - - // To ensure the key is deleted server-side. - Thread.sleep(30000); - - // We accidentally deleted the EC key. Let's recover it. - // A deleted key can only be recovered if the key vault is soft-delete enabled. - keyAsyncClient.beginRecoverDeletedKey("CloudEcKey") - .subscribe(pollResponse -> { - System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); - System.out.println("Recover Key Name: " + pollResponse.getValue().getName()); - System.out.println("Recover Key Type: " + pollResponse.getValue().getKeyType()); - }); - - // To ensure the key is recovered server-side before moving forward. - Thread.sleep(10000); - - // The EC and RSA keys are no longer needed, need to delete them from the key vault. - keyAsyncClient.beginDeleteKey("CloudEcKey") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); - System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); - }); - - keyAsyncClient.beginDeleteKey("CloudRsaKey") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); - System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); - }); - - // To ensure the key is deleted server-side. - Thread.sleep(30000); - - // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled. - keyAsyncClient.listDeletedKeys() - .subscribe(deletedKey -> - System.out.printf("Deleted key's recovery Id %s %n", deletedKey.getRecoveryId())); - - Thread.sleep(15000); - - // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. - keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey") - .subscribe(purgeResponse -> - System.out.printf("Storage account key purge status response %d %n", purgeResponse.getStatusCode())); - - keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey") - .subscribe(purgeResponse -> - System.out.printf("Bank account key purge status response %d %n", purgeResponse.getStatusCode())); - - // To ensure the key is purged server-side. - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java deleted file mode 100644 index 78e2859750b6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient; -import com.azure.security.keyvault.keys.cryptography.CryptographyClient; -import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyProperties; -import com.azure.security.keyvault.keys.models.KeyVaultKey; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.security.SecureRandom; -import java.time.OffsetDateTime; - -@SuppressWarnings("unused") -public class ReadmeSamples { - private static final byte[] SEED; - - static { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(bos); - byte[] seed; - try { - dos.writeLong(0x1234567L); - dos.flush(); - seed = bos.toByteArray(); - } catch (IOException ex) { - seed = new byte[0]; - } - - SEED = seed; - } - - private final KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - private final KeyAsyncClient keyAsyncClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - private final CryptographyClient cryptoClient = new CryptographyClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: readme-sample-createKeyClient - } - - public void createCryptographyClient() { - // BEGIN: readme-sample-createCryptographyClient - // Create client with key identifier from Key Vault. - CryptographyClient cryptoClient = new CryptographyClientBuilder() - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: readme-sample-createCryptographyClient - } - - public void createKey() { - // BEGIN: readme-sample-createKey - KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)); - System.out.printf("Key created with name \"%s\" and id %s%n", rsaKey.getName(), rsaKey.getId()); - - KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setCurveName(KeyCurveName.P_256) - .setExpiresOn(OffsetDateTime.now().plusYears(1))); - System.out.printf("Key created with name \"%s\" and id %s%n", ecKey.getName(), ecKey.getId()); - // END: readme-sample-createKey - } - - public void retrieveKey() { - // BEGIN: readme-sample-retrieveKey - KeyVaultKey key = keyClient.getKey(""); - System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName(), key.getId()); - // END: readme-sample-retrieveKey - } - - public void updateKey() { - // BEGIN: readme-sample-updateKey - // Get the key to update. - KeyVaultKey key = keyClient.getKey(""); - // Update the expiry time of the key. - key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); - KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties()); - System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn()); - // END: readme-sample-updateKey - } - - public void deleteKey() { - // BEGIN: readme-sample-deleteKey - SyncPoller deletedKeyPoller = keyClient.beginDeleteKey(""); - - PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); - - // Deleted key is accessible as soon as polling begins. - DeletedKey deletedKey = deletedKeyPollResponse.getValue(); - // Deletion date only works for a soft-delete enabled key vault. - System.out.printf("Deletion date: %s%n", deletedKey.getDeletedOn()); - - // The key is being deleted on the server. - deletedKeyPoller.waitForCompletion(); - // END: readme-sample-deleteKey - } - - public void listKeys() { - // BEGIN: readme-sample-listKeys - // List operations don't return the keys with key material information. So, for each returned key we call getKey to - // get the key with its key material information. - for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { - KeyVaultKey keyWithMaterial = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); - System.out.printf("Received key with name \"%s\" and type \"%s\"%n", keyWithMaterial.getName(), - keyWithMaterial.getKey().getKeyType()); - } - // END: readme-sample-listKeys - } - - public void encrypt() { - // BEGIN: readme-sample-encrypt - byte[] plaintext = new byte[100]; - new SecureRandom(SEED).nextBytes(plaintext); - - // Let's encrypt a simple plain text of size 100 bytes. - EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); - System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); - // END: readme-sample-encrypt - } - - public void decrypt() { - // BEGIN: readme-sample-decrypt - byte[] plaintext = new byte[100]; - new SecureRandom(SEED).nextBytes(plaintext); - EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); - - //Let's decrypt the encrypted result. - DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); - System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length); - // END: readme-sample-decrypt - } - - public void createKeyAsync() { - // BEGIN: readme-sample-createKeyAsync - keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)) - .subscribe(key -> - System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); - - keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) - .subscribe(key -> - System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); - // END: readme-sample-createKeyAsync - } - - public void retrieveKeyAsync() { - // BEGIN: readme-sample-retrieveKeyAsync - keyAsyncClient.getKey("") - .subscribe(key -> - System.out.printf("Key was returned with name \"%s\" and id %s%n", key.getName(), key.getId())); - // END: readme-sample-retrieveKeyAsync - } - - public void updateKeyAsync() { - // BEGIN: readme-sample-updateKeyAsync - keyAsyncClient.getKey("") - .flatMap(key -> { - // Update the expiry time of the key. - key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); - return keyAsyncClient.updateKeyProperties(key.getProperties()); - }).subscribe(updatedKey -> - System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); - // END: readme-sample-updateKeyAsync - } - - public void deleteKeyAsync() { - // BEGIN: readme-sample-deleteKeyAsync - keyAsyncClient.beginDeleteKey("") - .subscribe(pollResponse -> { - System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); - System.out.printf("Deleted key name: %s%n", pollResponse.getValue().getName()); - System.out.printf("Key deletion date: %s%n", pollResponse.getValue().getDeletedOn()); - }); - // END: readme-sample-deleteKeyAsync - } - - public void listKeysAsync() { - // BEGIN: readme-sample-listKeysAsync - // The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its value - // as well. - keyAsyncClient.listPropertiesOfKeys() - .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) - .subscribe(key -> - System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType())); - // END: readme-sample-listKeysAsync - } - - public void encryptAsync() { - // BEGIN: readme-sample-encryptAsync - byte[] plaintext = new byte[100]; - new SecureRandom(SEED).nextBytes(plaintext); - - // Let's encrypt a simple plain text of size 100 bytes. - cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .subscribe(encryptionResult -> System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm())); - // END: readme-sample-encryptAsync - } - - public void decryptAsync() { - // BEGIN: readme-sample-decryptAsync - byte[] plaintext = new byte[100]; - new SecureRandom(SEED).nextBytes(plaintext); - - // Let's encrypt a simple plain text of size 100 bytes. - cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .flatMap(encryptionResult -> { - System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); - //Let's decrypt the encrypted response. - return cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); - }).subscribe(decryptionResult -> - System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); - // END: readme-sample-decryptAsync - } - - public void troubleshooting() { - // BEGIN: readme-sample-troubleshooting - try { - keyClient.getKey(""); - } catch (ResourceNotFoundException e) { - System.out.println(e.getMessage()); - } - // END: readme-sample-troubleshooting - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClientJavaDocCodeSnippets.java deleted file mode 100644 index 3dc44cbd7474..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import reactor.util.context.Context; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Random; - -/** - * This class contains code samples for generating javadocs through doclets for {@link CryptographyAsyncClient}. - */ -public final class CryptographyAsyncClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link CryptographyAsyncClient}. - * - * @return An instance of {@link CryptographyAsyncClient}. - */ - public CryptographyAsyncClient createAsyncClient() { - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation - CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation - - return cryptographyAsyncClient; - } - - /** - * Generates a code sample for creating a {@link CryptographyAsyncClient} with a given {@link JsonWebKey}. - * - * @return An instance of {@link CryptographyAsyncClient}. - */ - public CryptographyAsyncClient createAsyncClientWithJsonWebKey() { - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation - JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey"); - CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() - .jsonWebKey(jsonWebKey) - .buildAsyncClient(); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation - - return cryptographyAsyncClient; - } - - /** - * Generates a code sample for creating a {@link CryptographyAsyncClient} with a given {@link HttpClient}. - * - * @return An instance of {@link CryptographyAsyncClient}. - */ - public CryptographyAsyncClient createAsyncClientWithHttpClient() { - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation - CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .httpClient(HttpClient.createDefault()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation - - return cryptographyAsyncClient; - } - - /** - * Generates a code sample for using {@link CryptographyAsyncClient#getKey()}. - */ - public void getKeySnippets() { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey - cryptographyAsyncClient.getKey() - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(key -> - System.out.printf("Key returned with name: %s, and id: %s.%n", key.getName(), key.getId())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey - } - - /** - * Generates a code sample for using {@link CryptographyAsyncClient#getKeyWithResponse()}. - */ - public void getKeyWithResponseSnippets() { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse - cryptographyAsyncClient.getKeyWithResponse() - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(keyResponse -> - System.out.printf("Key returned with name: %s, and id: %s.%n", keyResponse.getValue().getName(), - keyResponse.getValue().getId())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse - } - - /** - * Generates code samples for using {@link CryptographyAsyncClient#encrypt(EncryptionAlgorithm, byte[])} and - * {@link CryptographyAsyncClient#encrypt(EncryptParameters)}. - */ - public void encrypt() { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte - byte[] plaintext = new byte[100]; - new Random(0x1234567L).nextBytes(plaintext); - - cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(encryptResult -> - System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", - encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters - byte[] plaintextBytes = new byte[100]; - new Random(0x1234567L).nextBytes(plaintextBytes); - byte[] iv = { - (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, - (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 - }; - - EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(plaintextBytes, iv); - - cryptographyAsyncClient.encrypt(encryptParameters) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(encryptResult -> - System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", - encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters - } - - /** - * Generates code samples for using {@link CryptographyAsyncClient#decrypt(EncryptionAlgorithm, byte[])} and - * {@link CryptographyAsyncClient#decrypt(DecryptParameters)}. - */ - public void decrypt() { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte - byte[] ciphertext = new byte[100]; - new Random(0x1234567L).nextBytes(ciphertext); - - cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(decryptResult -> - System.out.printf("Received decrypted content of length: %d%n", decryptResult.getPlainText().length)); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters - byte[] ciphertextBytes = new byte[100]; - new Random(0x1234567L).nextBytes(ciphertextBytes); - byte[] iv = { - (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, - (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 - }; - - DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(ciphertextBytes, iv); - - cryptographyAsyncClient.decrypt(decryptParameters) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(decryptResult -> - System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length)); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters - } - - /** - * Generates a code sample for using {@link CryptographyAsyncClient#sign(SignatureAlgorithm, byte[])} and - * {@link CryptographyAsyncClient#verify(SignatureAlgorithm, byte[], byte[])}. - * - * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. - */ - public void signVerify() throws NoSuchAlgorithmException { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte - byte[] data = new byte[100]; - new Random(0x1234567L).nextBytes(data); - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(data); - byte[] digest = md.digest(); - - cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, digest) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(signResult -> - System.out.printf("Received signature of length: %d, with algorithm: %s.%n", - signResult.getSignature().length, signResult.getAlgorithm())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte - - byte[] signature = new byte[100]; - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte - byte[] myData = new byte[100]; - new Random(0x1234567L).nextBytes(myData); - MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); - messageDigest.update(myData); - byte[] myDigest = messageDigest.digest(); - - // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation. - cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myDigest, signature) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(verifyResult -> - System.out.printf("Verification status: %s.%n", verifyResult.isValid())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte - } - - - /** - * Generates a code sample for using {@link CryptographyAsyncClient#wrapKey(KeyWrapAlgorithm, byte[])} and - * {@link CryptographyAsyncClient#unwrapKey(KeyWrapAlgorithm, byte[])}. - */ - public void wrapKeyUnwrapKey() { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte - byte[] key = new byte[100]; - new Random(0x1234567L).nextBytes(key); - - cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(wrapResult -> - System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", - wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm().toString())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte - byte[] keyToWrap = new byte[100]; - new Random(0x1234567L).nextBytes(key); - - cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(wrapResult -> - cryptographyAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapResult.getEncryptedKey()) - .subscribe(keyUnwrapResult -> - System.out.printf("Received key of length: %d.%n", keyUnwrapResult.getKey().length))); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte - } - - /** - * Generates a code sample for using {@link CryptographyAsyncClient#signData(SignatureAlgorithm, byte[])} and - * {@link CryptographyAsyncClient#verifyData(SignatureAlgorithm, byte[], byte[])}. - * - * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. - */ - public void signDataVerifyData() throws NoSuchAlgorithmException { - CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte - byte[] data = new byte[100]; - new Random(0x1234567L).nextBytes(data); - - cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, data) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(signResult -> - System.out.printf("Received signature of length: %d, with algorithm: %s.%n", - signResult.getSignature().length, signResult.getAlgorithm())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte - - byte[] signature = new byte[100]; - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte - byte[] myData = new byte[100]; - new Random(0x1234567L).nextBytes(myData); - - // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation. - cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myData, signature) - .contextWrite(Context.of("key1", "value1", "key2", "value2")) - .subscribe(verifyResult -> - System.out.printf("Verification status: %s.%n", verifyResult.isValid())); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientJavaDocCodeSnippets.java deleted file mode 100644 index 22db104a87e9..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.util.Context; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyVaultKey; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Random; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyClient}. - */ -public final class CryptographyClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link CryptographyClient}. - * - * @return An instance of {@link CryptographyClient}. - */ - public CryptographyClient createClient() { - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation - CryptographyClient cryptographyClient = new CryptographyClientBuilder() - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation - - return cryptographyClient; - } - - /** - * Generates a code sample for creating a {@link CryptographyClient} with a given {@link JsonWebKey}. - * - * @return An instance of {@link CryptographyClient}. - */ - public CryptographyClient createClientWithJsonWebKey() { - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation - JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey"); - CryptographyClient cryptographyClient = new CryptographyClientBuilder() - .jsonWebKey(jsonWebKey) - .buildClient(); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation - - return cryptographyClient; - } - - /** - * Generates a code sample for using {@link CryptographyClient#getKey()}. - */ - public void getKeySnippets() { - CryptographyClient cryptographyClient = createClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey - KeyVaultKey key = cryptographyClient.getKey(); - - System.out.printf("Key returned with name: %s and id: %s.%n", key.getName(), key.getId()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey - } - - /** - * Generates a code sample for using {@link CryptographyClient#getKeyWithResponse(Context)}. - */ - public void getKeyWithResponseSnippets() { - CryptographyClient cryptographyClient = createClient(); - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context - KeyVaultKey keyWithVersion = cryptographyClient.getKeyWithResponse(new Context("key1", "value1")).getValue(); - - System.out.printf("Key is returned with name: %s and id %s.%n", keyWithVersion.getName(), - keyWithVersion.getId()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context - } - - /** - * Generates a code sample for using {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[])}, - * {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[], Context)} and - * {@link CryptographyClient#encrypt(EncryptParameters, Context)}. - */ - public void encrypt() { - CryptographyClient cryptographyClient = createClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte - byte[] plaintext = new byte[100]; - new Random(0x1234567L).nextBytes(plaintext); - - EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); - - System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", - encryptResult.getCipherText().length, encryptResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context - byte[] plaintextToEncrypt = new byte[100]; - new Random(0x1234567L).nextBytes(plaintextToEncrypt); - - EncryptResult encryptionResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintextToEncrypt, - new Context("key1", "value1")); - - System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context - byte[] myPlaintext = new byte[100]; - new Random(0x1234567L).nextBytes(myPlaintext); - byte[] iv = { - (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, - (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 - }; - - EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(myPlaintext, iv); - EncryptResult encryptedResult = cryptographyClient.encrypt(encryptParameters, new Context("key1", "value1")); - - System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", - encryptedResult.getCipherText().length, encryptedResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context - } - - /** - * Generates a code sample for using {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[])}, - * {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[], Context)} and - * {@link CryptographyClient#decrypt(DecryptParameters, Context)}. - */ - public void decrypt() { - CryptographyClient cryptographyClient = createClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte - byte[] ciphertext = new byte[100]; - new Random(0x1234567L).nextBytes(ciphertext); - - DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext); - - System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context - byte[] ciphertextToDecrypt = new byte[100]; - new Random(0x1234567L).nextBytes(ciphertextToDecrypt); - - DecryptResult decryptionResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertextToDecrypt, - new Context("key1", "value1")); - - System.out.printf("Received decrypted content of length: %d.%n", decryptionResult.getPlainText().length); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context - byte[] myCiphertext = new byte[100]; - new Random(0x1234567L).nextBytes(myCiphertext); - byte[] iv = { - (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, - (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 - }; - - DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(myCiphertext, iv); - DecryptResult decryptedResult = cryptographyClient.decrypt(decryptParameters, new Context("key1", "value1")); - - System.out.printf("Received decrypted content of length: %d.%n", decryptedResult.getPlainText().length); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context - } - - /** - * Generates a code sample for using {@link CryptographyClient#sign(SignatureAlgorithm, byte[])} and - * {@link CryptographyClient#verify(SignatureAlgorithm, byte[], byte[])}. - * - * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. - */ - public void signVerify() throws NoSuchAlgorithmException { - CryptographyClient cryptographyClient = createClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte - byte[] data = new byte[100]; - new Random(0x1234567L).nextBytes(data); - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(data); - byte[] digest = md.digest(); - - SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, digest); - - System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length, - signResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context - byte[] dataToVerify = new byte[100]; - new Random(0x1234567L).nextBytes(dataToVerify); - MessageDigest myMessageDigest = MessageDigest.getInstance("SHA-256"); - myMessageDigest.update(dataToVerify); - byte[] digestContent = myMessageDigest.digest(); - - SignResult signResponse = cryptographyClient.sign(SignatureAlgorithm.ES256, digestContent, - new Context("key1", "value1")); - - System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResponse.getSignature().length, - signResponse.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context - - byte[] signature = signResult.getSignature(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte - byte[] myData = new byte[100]; - new Random(0x1234567L).nextBytes(myData); - MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); - messageDigest.update(myData); - byte[] myDigest = messageDigest.digest(); - - // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. - VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myDigest, signature); - - System.out.printf("Verification status: %s.%n", verifyResult.isValid()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte - - byte[] signatureBytes = signResponse.getSignature(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context - byte[] dataBytes = new byte[100]; - new Random(0x1234567L).nextBytes(dataBytes); - MessageDigest msgDigest = MessageDigest.getInstance("SHA-256"); - msgDigest.update(dataBytes); - byte[] digestBytes = msgDigest.digest(); - - // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. - VerifyResult verifyResponse = cryptographyClient.verify(SignatureAlgorithm.ES256, digestBytes, signatureBytes, - new Context("key1", "value1")); - - System.out.printf("Verification status: %s.%n", verifyResponse.isValid()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context - } - - - /** - * Generates a code sample for using {@link CryptographyClient#wrapKey(KeyWrapAlgorithm, byte[])}, - * {@link CryptographyClient#wrapKey(KeyWrapAlgorithm, byte[], Context)}, - * {@link CryptographyClient#unwrapKey(KeyWrapAlgorithm, byte[])} and - * {@link CryptographyClient#unwrapKey(KeyWrapAlgorithm, byte[], Context)}. - */ - public void wrapKeyUnwrapKey() { - CryptographyClient cryptographyClient = createClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte - byte[] key = new byte[100]; - new Random(0x1234567L).nextBytes(key); - - WrapResult wrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key); - - System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", - wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context - byte[] keyToWrap = new byte[100]; - new Random(0x1234567L).nextBytes(keyToWrap); - - WrapResult keyWrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap, - new Context("key1", "value1")); - - System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", - keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte - byte[] keyContent = new byte[100]; - new Random(0x1234567L).nextBytes(keyContent); - - WrapResult wrapKeyResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContent, - new Context("key1", "value1")); - UnwrapResult unwrapResult = cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, - wrapKeyResult.getEncryptedKey()); - - System.out.printf("Received key of length %d", unwrapResult.getKey().length); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context - byte[] keyContentToWrap = new byte[100]; - new Random(0x1234567L).nextBytes(keyContentToWrap); - Context context = new Context("key1", "value1"); - - WrapResult wrapKeyContentResult = - cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContentToWrap, context); - UnwrapResult unwrapKeyResponse = - cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapKeyContentResult.getEncryptedKey(), context); - - System.out.printf("Received key of length %d", unwrapKeyResponse.getKey().length); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context - } - - /** - * Generates a code sample for using {@link CryptographyClient#signData(SignatureAlgorithm, byte[])} and - * {@link CryptographyClient#verifyData(SignatureAlgorithm, byte[], byte[])}. - * - * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. - */ - public void signDataVerifyData() throws NoSuchAlgorithmException { - CryptographyClient cryptographyClient = createClient(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte - byte[] data = new byte[32]; - new Random(0x1234567L).nextBytes(data); - - SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, data); - - System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length, - signResult.getAlgorithm()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context - byte[] plainTextData = new byte[32]; - new Random(0x1234567L).nextBytes(plainTextData); - - SignResult signingResult = cryptographyClient.sign(SignatureAlgorithm.ES256, plainTextData); - - System.out.printf("Received signature of length: %d, with algorithm: %s.%n", - signingResult.getSignature().length, new Context("key1", "value1")); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context - - byte[] signature = signResult.getSignature(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte - byte[] myData = new byte[32]; - new Random(0x1234567L).nextBytes(myData); - - // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. - VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myData, signature); - - System.out.printf("Verification status: %s.%n", verifyResult.isValid()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte - - byte[] mySignature = signingResult.getSignature(); - - // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context - byte[] dataToVerify = new byte[32]; - new Random(0x1234567L).nextBytes(dataToVerify); - - // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. - VerifyResult verificationResult = cryptographyClient.verify(SignatureAlgorithm.ES256, dataToVerify, - mySignature, new Context("key1", "value1")); - - System.out.printf("Verification status: %s.%n", verificationResult.isValid()); - // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperations.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperations.java deleted file mode 100644 index 6fea13cd83a5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/EncryptDecryptOperations.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; - -import java.util.Random; - -/** - * Sample demonstrates how to set, get, update and delete a key. - */ -public class EncryptDecryptOperations { - /** - * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException, IllegalArgumentException { - /* Instantiate a CryptographyClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a key identifier for a key stored in a key vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - CryptographyClient cryptoClient = new CryptographyClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .keyIdentifier("") - .buildAsyncClient(); - - byte[] plaintext = new byte[100]; - new Random(0x1234567L).nextBytes(plaintext); - - // Let's encrypt a simple plain text of size 100 bytes. - cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .subscribe(encryptResult -> { - System.out.printf("Returned ciphertext size is %d bytes with algorithm %s\n", - encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()); - // Let's decrypt the encrypted response. - cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptResult.getCipherText()) - .subscribe(decryptResult -> System.out.printf("Returned plaintext size is %d bytes\n", - decryptResult.getPlainText().length)); - }); - - Thread.sleep(5000); - } -} - diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperations.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperations.java deleted file mode 100644 index e1edd93564e4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperations.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; -import com.azure.security.keyvault.keys.cryptography.models.WrapResult; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; - -import java.util.Random; - - -/** - * Sample demonstrates how to set, get, update and delete a key. - */ -public class KeyWrapUnwrapOperations { - /** - * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException, IllegalArgumentException { - /* Instantiate a CryptographyClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a key identifier for a key stored in a key vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - CryptographyClient cryptoClient = new CryptographyClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .keyIdentifier("") - .buildAsyncClient(); - - byte[] plaintext = new byte[100]; - new Random(0x1234567L).nextBytes(plaintext); - - // Let's wrap a simple dummy key content. - cryptoAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, plaintext) - .subscribe(keyWrapResult -> { - System.out.printf("Returned encrypted key size is %d bytes with algorithm %s\n", - keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm().toString()); - // Let's decrypt the encrypted response. - cryptoAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, keyWrapResult.getEncryptedKey()) - .subscribe(keyUnwrapResult -> - System.out.printf("Returned unwrapped key size is %d bytes\n", keyUnwrapResult.getKey().length)); - }); - - Thread.sleep(5000); - - // Let's do Key Wrap and Unwrap operations with a symmetric key. - byte[] symmetricKeyContent = - {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; - byte[] keyContentToWrap = - {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, - (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF}; - } -} - diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperations.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperations.java deleted file mode 100644 index 9938158a6ded..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/SignVerifyOperations.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Random; - -/** - * Sample demonstrates how to set, get, update and delete a key. - */ -public class SignVerifyOperations { - /** - * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. - */ - public static void main(String[] args) throws InterruptedException, IllegalArgumentException, NoSuchAlgorithmException { - /* Instantiate a CryptographyClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a key identifier for a key stored in a key vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) - for links and instructions. */ - CryptographyClient cryptoClient = new CryptographyClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .keyIdentifier("") - .buildAsyncClient(); - - byte[] plaintext = new byte[100]; - new Random(0x1234567L).nextBytes(plaintext); - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(plaintext); - byte[] digest = md.digest(); - - // Let's create a signature from a simple digest. - cryptoAsyncClient.sign(SignatureAlgorithm.RS256, digest) - .subscribe(signResult -> { - System.out.printf("Returned signature size is %d bytes with algorithm %s\n", - signResult.getSignature().length, signResult.getAlgorithm().toString()); - // Let's verify the signature against the digest. - cryptoAsyncClient.verify(SignatureAlgorithm.RS256, digest, signResult.getSignature()) - .subscribe(verifyResult -> - System.out.printf("Signature verified : %s\n", verifyResult.isValid())); - }); - - Thread.sleep(4000); - - // We can sign the raw plain text data without having to create a digest. - cryptoAsyncClient.sign(SignatureAlgorithm.RS256, digest) - .subscribe(signResult -> { - System.out.printf("Returned signature size is %d bytes with algorithm %s\n", - signResult.getSignature().length, signResult.getAlgorithm().toString()); - // Let's verify the signature against the raw plain text data. - cryptoAsyncClient.verify(SignatureAlgorithm.RS256, digest, signResult.getSignature()) - .subscribe(verifyDataResult -> - System.out.printf("Signature verified : %s\n", verifyDataResult.isValid())); - }); - - // Block main thread to let async operations finish. - Thread.sleep(4000); - } -} - diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientManagedHsmTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientManagedHsmTest.java deleted file mode 100644 index 97b41a6cc50c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientManagedHsmTest.java +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys; - -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.http.HttpClient; -import com.azure.core.test.TestMode; -import com.azure.core.util.Configuration; -import com.azure.security.keyvault.keys.models.KeyType; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.condition.EnabledIf; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.test.StepVerifier; - -import java.math.BigInteger; -import java.net.HttpURLConnection; - -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertEquals; - -@EnabledIf("shouldRunHsmTest") -public class KeyAsyncClientManagedHsmTest extends KeyAsyncClientTest implements KeyClientManagedHsmTestBase { - public KeyAsyncClientManagedHsmTest() { - this.isHsmEnabled = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; - this.runManagedHsmTest = shouldRunHsmTest(); - } - - public static boolean shouldRunHsmTest() { - return Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null - || TEST_MODE == TestMode.PLAYBACK; - } - - /** - * Tests that an RSA key created. - */ - @Override - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - super.createRsaKey(httpClient, serviceVersion); - } - - /** - * Tests that an RSA key with a public exponent can be created in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createRsaKeyWithPublicExponentRunner( - (keyToCreate) -> StepVerifier.create(keyAsyncClient.createRsaKey(keyToCreate)).assertNext(rsaKey -> { - assertKeyEquals(keyToCreate, rsaKey); - assertEquals(BigInteger.valueOf(keyToCreate.getPublicExponent()), toBigInteger(rsaKey.getKey().getE())); - assertEquals(keyToCreate.getKeySize(), rsaKey.getKey().getN().length * 8); - }).verifyComplete()); - } - - /** - * Tests that a symmetric key is created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createOctKeyWithDefaultSize(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createOctKeyRunner(null, - (keyToCreate) -> StepVerifier.create(keyAsyncClient.createOctKey(keyToCreate)).assertNext(octKey -> { - assertEquals(keyToCreate.getName(), octKey.getName()); - assertEquals(KeyType.OCT_HSM, octKey.getKey().getKeyType()); - assertEquals(keyToCreate.getExpiresOn(), octKey.getProperties().getExpiresOn()); - assertEquals(keyToCreate.getNotBefore(), octKey.getProperties().getNotBefore()); - assertEquals(keyToCreate.getTags(), octKey.getProperties().getTags()); - }).verifyComplete()); - } - - /** - * Tests that a symmetric key of a valid size is created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createOctKeyWithValidSize(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createOctKeyRunner(256, - (keyToCreate) -> StepVerifier.create(keyAsyncClient.createOctKey(keyToCreate)).assertNext(octKey -> { - assertEquals(keyToCreate.getName(), octKey.getName()); - assertEquals(KeyType.OCT_HSM, octKey.getKey().getKeyType()); - assertEquals(keyToCreate.getExpiresOn(), octKey.getProperties().getExpiresOn()); - assertEquals(keyToCreate.getNotBefore(), octKey.getProperties().getNotBefore()); - assertEquals(keyToCreate.getTags(), octKey.getProperties().getTags()); - }).verifyComplete()); - } - - /** - * Tests that a symmetric key of an invalid size cannot be created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createOctKeyWithInvalidSize(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createOctKeyRunner(64, - (keyToCreate) -> StepVerifier.create(keyAsyncClient.createOctKey(keyToCreate)) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); - } - - /** - * Tests that random bytes can be retrieved from a Managed HSM. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getRandomBytes(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - getRandomBytesRunner((count) -> StepVerifier.create(keyAsyncClient.getRandomBytes(count)) - .assertNext(randomBytes -> assertEquals(count, randomBytes.length)) - .verifyComplete()); - } - - /** - * Tests that an existing key can be released. - */ - @Override - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Ignoring test until the service rolls out a fix for an issue with the "version" parameter of a release - // policy. - Assumptions.assumeTrue(serviceVersion != KeyServiceVersion.V7_4); - - super.releaseKey(httpClient, serviceVersion); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java deleted file mode 100644 index 77baddcaa089..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java +++ /dev/null @@ -1,830 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpClient; -import com.azure.core.test.TestMode; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.core.util.polling.AsyncPollResponse; -import com.azure.core.util.polling.PollerFlux; -import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient; -import com.azure.security.keyvault.keys.cryptography.CryptographyClient; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.keys.models.CreateKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -import com.azure.security.keyvault.keys.models.KeyType; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.condition.DisabledIfSystemProperty; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.net.HttpURLConnection; - -import static com.azure.security.keyvault.keys.TestUtils.buildAsyncAssertingClient; -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyAsyncClientTest extends KeyClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(KeyAsyncClientTest.class); - protected KeyAsyncClient keyAsyncClient; - - @Override - protected void beforeTest() { - beforeTestSetup(); - } - - protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion, null); - } - - protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) { - keyAsyncClient = getKeyClientBuilder( - buildAsyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - testTenantId, getEndpoint(), serviceVersion).buildAsyncClient(); - } - - /** - * Tests that a key can be created in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createKeyRunner( - (keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)).assertNext(createdKey -> { - assertKeyEquals(keyToCreate, createdKey); - - if (!isHsmEnabled) { - assertEquals("0", createdKey.getProperties().getHsmPlatform()); - } - }).verifyComplete()); - } - - /** - * Tests that a key can be created in the key vault while using a different tenant ID than the one that will be - * provided in the authentication challenge. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); - - createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) - .assertNext(response -> assertKeyEquals(keyToCreate, response)) - .verifyComplete()); - - KeyVaultCredentialPolicy.clearCache(); // Ensure we don't have anything cached and try again. - - createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) - .assertNext(response -> assertKeyEquals(keyToCreate, response)) - .verifyComplete()); - } - - /** - * Tests that a RSA key created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createRsaKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createRsaKey(keyToCreate)) - .assertNext(response -> assertKeyEquals(keyToCreate, response)) - .verifyComplete()); - } - - /** - * Tests that we cannot create a key when the key is an empty string. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - final KeyType keyType; - - if (runManagedHsmTest) { - keyType = KeyType.RSA_HSM; - } else { - keyType = KeyType.RSA; - } - - StepVerifier.create(keyAsyncClient.createKey("", keyType)) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); - } - - /** - * Tests that we can create keys when value is not null or an empty string. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createKeyEmptyValueRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); - } - - /** - * Verifies that an exception is thrown when null key object is passed for creation. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(keyAsyncClient.createKey(null)).verifyError(NullPointerException.class); - } - - /** - * Tests that a key is able to be updated when it exists. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - updateKeyRunner( - (originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey).flatMap(response -> { - assertKeyEquals(originalKey, response); - - return keyAsyncClient - .updateKeyProperties(response.getProperties().setExpiresOn(updatedKey.getExpiresOn())); - })).assertNext(response -> assertKeyEquals(updatedKey, response)).verifyComplete()); - } - - /** - * Tests that a key is not able to be updated when it is disabled. 403 error is expected. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - updateDisabledKeyRunner( - (originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey).flatMap(response -> { - assertKeyEquals(originalKey, response); - - return keyAsyncClient - .updateKeyProperties(response.getProperties().setExpiresOn(updatedKey.getExpiresOn())); - })).assertNext(response -> assertKeyEquals(updatedKey, response)).verifyComplete()); - } - - /** - * Tests that an existing key can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - getKeyRunner((keyToSetAndGet) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToSetAndGet)).assertNext(createdKey -> { - assertKeyEquals(keyToSetAndGet, createdKey); - - if (!isHsmEnabled) { - assertEquals("0", createdKey.getProperties().getHsmPlatform()); - } - }).verifyComplete(); - - StepVerifier.create(keyAsyncClient.getKey(keyToSetAndGet.getName())).assertNext(retrievedKey -> { - assertKeyEquals(keyToSetAndGet, retrievedKey); - - if (!isHsmEnabled) { - assertEquals("0", retrievedKey.getProperties().getHsmPlatform()); - } - }).verifyComplete(); - }); - } - - /** - * Tests that a specific version of the key can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - getKeySpecificVersionRunner((keyWithOriginalValue, keyWithNewValue) -> { - StepVerifier - .create(keyAsyncClient.createKey(keyWithOriginalValue) - .flatMap(keyVersionOne -> keyAsyncClient.getKey(keyWithOriginalValue.getName(), - keyVersionOne.getProperties().getVersion()))) - .assertNext(response -> assertKeyEquals(keyWithOriginalValue, response)) - .verifyComplete(); - - StepVerifier - .create(keyAsyncClient.createKey(keyWithNewValue) - .flatMap(keyVersionTwo -> keyAsyncClient.getKey(keyWithNewValue.getName(), - keyVersionTwo.getProperties().getVersion()))) - .assertNext(response -> assertKeyEquals(keyWithNewValue, response)) - .verifyComplete(); - }); - } - - /** - * Tests that an attempt to get a non-existing key throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(keyAsyncClient.getKey("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that an existing key can be deleted. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - deleteKeyRunner((keyToDelete) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToDelete)) - .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)) - .verifyComplete(); - - PollerFlux poller - = setPlaybackPollerFluxPollInterval(keyAsyncClient.beginDeleteKey(keyToDelete.getName())); - - StepVerifier.create(poller.last().map(AsyncPollResponse::getValue)).assertNext(deletedKeyResponse -> { - assertNotNull(deletedKeyResponse.getDeletedOn()); - assertNotNull(deletedKeyResponse.getRecoveryId()); - assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); - assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); - }).verifyComplete(); - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(keyAsyncClient.beginDeleteKey("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - StepVerifier.create(keyAsyncClient.getDeletedKey("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a deleted key can be recovered on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndRecover)) - .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)) - .verifyComplete(); - - PollerFlux poller - = setPlaybackPollerFluxPollInterval(keyAsyncClient.beginDeleteKey(keyToDeleteAndRecover.getName())); - - StepVerifier.create(poller.last()).expectNextCount(1).verifyComplete(); - - PollerFlux recoverPoller = setPlaybackPollerFluxPollInterval( - keyAsyncClient.beginRecoverDeletedKey(keyToDeleteAndRecover.getName())); - - StepVerifier.create(recoverPoller.last().map(AsyncPollResponse::getValue)).assertNext(keyResponse -> { - assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); - assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); - assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(keyAsyncClient.beginRecoverDeletedKey("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a key can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - backupKeyRunner((keyToBackup) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToBackup)) - .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)) - .verifyComplete(); - - StepVerifier.create(keyAsyncClient.backupKey(keyToBackup.getName())).assertNext(response -> { - assertNotNull(response); - assertTrue(response.length > 0); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to backup a non existing key throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(keyAsyncClient.backupKey("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a key can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - restoreKeyRunner((keyToBackupAndRestore) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToBackupAndRestore)) - .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)) - .verifyComplete(); - - byte[] backup = keyAsyncClient.backupKey(keyToBackupAndRestore.getName()).block(); - - PollerFlux poller - = setPlaybackPollerFluxPollInterval(keyAsyncClient.beginDeleteKey(keyToBackupAndRestore.getName())); - - StepVerifier.create(poller.last()).expectNextCount(1).verifyComplete(); - - StepVerifier.create(keyAsyncClient.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) - .assertNext( - voidResponse -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode())) - .verifyComplete(); - - pollOnKeyPurge(keyToBackupAndRestore.getName()); - - sleepIfRunningAgainstService(60000); - - StepVerifier.create(keyAsyncClient.restoreKeyBackup(backup)).assertNext(response -> { - assertEquals(keyToBackupAndRestore.getName(), response.getName()); - assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); - assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to restore a key from malformed backup bytes throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - byte[] keyBackupBytes = "non-existing".getBytes(); - - StepVerifier.create(keyAsyncClient.restoreKeyBackup(keyBackupBytes)) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); - } - - /** - * Tests that a deleted key can be retrieved on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - getDeletedKeyRunner((keyToDeleteAndGet) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndGet)) - .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)) - .verifyComplete(); - - PollerFlux poller - = setPlaybackPollerFluxPollInterval(keyAsyncClient.beginDeleteKey(keyToDeleteAndGet.getName())); - - StepVerifier.create(poller.last()).expectNextCount(1).verifyComplete(); - - StepVerifier.create(keyAsyncClient.getDeletedKey(keyToDeleteAndGet.getName())) - .assertNext(deletedKeyResponse -> { - assertNotNull(deletedKeyResponse.getDeletedOn()); - assertNotNull(deletedKeyResponse.getRecoveryId()); - assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); - assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); - }) - .verifyComplete(); - }); - } - - /** - * Tests that deleted keys can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - // Skip when running against the service to avoid having pipeline runs take longer than they have to. - if (interceptorManager.isLiveMode()) { - return; - } - - listDeletedKeysRunner((keysToList) -> { - for (CreateKeyOptions key : keysToList.values()) { - StepVerifier.create(keyAsyncClient.createKey(key)) - .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) - .verifyComplete(); - } - - sleepIfRunningAgainstService(10000); - - for (CreateKeyOptions key : keysToList.values()) { - PollerFlux poller - = setPlaybackPollerFluxPollInterval(keyAsyncClient.beginDeleteKey(key.getName())); - - StepVerifier.create(poller.last()).expectNextCount(1).verifyComplete(); - } - - sleepIfRunningAgainstService(90000); - - StepVerifier.create(keyAsyncClient.listDeletedKeys().doOnNext(actualKey -> { - assertNotNull(actualKey.getDeletedOn()); - assertNotNull(actualKey.getRecoveryId()); - }).last()).expectNextCount(1).verifyComplete(); - }); - } - - /** - * Tests that key versions can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - listKeyVersionsRunner((keysToList) -> { - String keyName = null; - - for (CreateKeyOptions key : keysToList) { - keyName = key.getName(); - - StepVerifier.create(keyAsyncClient.createKey(key)) - .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) - .verifyComplete(); - } - - sleepIfRunningAgainstService(30000); - - StepVerifier.create(keyAsyncClient.listPropertiesOfKeyVersions(keyName).collectList()) - .assertNext(actualKeys -> assertEquals(keysToList.size(), actualKeys.size())) - .verifyComplete(); - }); - - } - - /** - * Tests that keys can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - listKeysRunner((keysToList) -> { - for (CreateKeyOptions key : keysToList.values()) { - StepVerifier.create(keyAsyncClient.createKey(key)) - .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) - .verifyComplete(); - } - - sleepIfRunningAgainstService(10000); - - StepVerifier.create(keyAsyncClient.listPropertiesOfKeys().map(actualKey -> { - if (keysToList.containsKey(actualKey.getName())) { - CreateKeyOptions expectedKey = keysToList.get(actualKey.getName()); - assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); - assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); - keysToList.remove(actualKey.getName()); - } - - return actualKey; - }).last()).expectNextCount(1).verifyComplete(); - - assertEquals(0, keysToList.size()); - }); - } - - /** - * Tests that an existing key can be released. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // TODO: Remove assumption once Key Vault allows for creating exportable keys. - Assumptions.assumeTrue(runManagedHsmTest && runReleaseKeyTest); - - createKeyAsyncClient(httpClient, serviceVersion); - - releaseKeyRunner((keyToRelease, attestationUrl) -> { - StepVerifier.create(keyAsyncClient.createRsaKey(keyToRelease)) - .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)) - .verifyComplete(); - - String targetAttestationToken = "testAttestationToken"; - - if (getTestMode() != TestMode.PLAYBACK) { - if (!attestationUrl.endsWith("/")) { - attestationUrl = attestationUrl + "/"; - } - - targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token"); - } - - StepVerifier.create(keyAsyncClient.releaseKey(keyToRelease.getName(), targetAttestationToken)) - .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) - .expectComplete() - .verify(); - }); - } - - /** - * Tests that fetching the key rotation policy of a non-existent key throws. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that fetching the key rotation policy of a non-existent key throws. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyAsyncClient(httpClient, serviceVersion); - - String keyName = testResourceNamer.randomName("rotateKey", 20); - - StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); - - StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(keyName)).assertNext(keyRotationPolicy -> { - assertNotNull(keyRotationPolicy); - assertNull(keyRotationPolicy.getId()); - assertNull(keyRotationPolicy.getCreatedOn()); - assertNull(keyRotationPolicy.getUpdatedOn()); - assertNull(keyRotationPolicy.getExpiresIn()); - assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); - assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction()); - assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); - assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); - }).verifyComplete(); - } - - /** - * Tests that fetching the key rotation policy of a non-existent key throws. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @Disabled("Disable after https://github.com/Azure/azure-sdk-for-java/issues/31510 is fixed.") - //@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, - KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyAsyncClient(httpClient, serviceVersion); - - updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> { - StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); - - StepVerifier - .create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) - .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), - keyAsyncClient.getKeyRotationPolicy(keyName)))) - .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) - .verifyComplete(); - }); - } - - /** - * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyAsyncClient(httpClient, serviceVersion); - - updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> { - StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); - - StepVerifier - .create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) - .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), - keyAsyncClient.getKeyRotationPolicy(keyName)))) - .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) - .verifyComplete(); - }); - } - - /** - * Tests that a key can be rotated. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyAsyncClient(httpClient, serviceVersion); - - String keyName = testResourceNamer.randomName("rotateKey", 20); - - StepVerifier - .create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName)) - .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), keyAsyncClient.rotateKey(keyName)))) - .assertNext(tuple -> { - KeyVaultKey createdKey = tuple.getT1(); - KeyVaultKey rotatedKey = tuple.getT2(); - - assertEquals(createdKey.getName(), rotatedKey.getName()); - assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); - }) - .verifyComplete(); - } - - /** - * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey"); - - assertNotNull(cryptographyAsyncClient); - } - - /** - * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests - * that cryptographic operations can be performed with said cryptography client. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - createKeyRunner((keyToCreate) -> { - StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) - .assertNext(response -> assertKeyEquals(keyToCreate, response)) - .verifyComplete(); - - CryptographyAsyncClient cryptographyAsyncClient - = keyAsyncClient.getCryptographyAsyncClient(keyToCreate.getName()); - - assertNotNull(cryptographyAsyncClient); - - byte[] plaintext = "myPlaintext".getBytes(); - - StepVerifier - .create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .map(EncryptResult::getCipherText) - .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) - .map(DecryptResult::getPlainText))) - .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) - .verifyComplete(); - }); - } - - /** - * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a - * {@link KeyAsyncClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - CryptographyAsyncClient cryptographyAsyncClient - = keyAsyncClient.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); - - assertNotNull(cryptographyAsyncClient); - } - - /** - * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", ""); - - assertNotNull(cryptographyAsyncClient); - } - - /** - * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyAsyncClient(httpClient, serviceVersion); - - CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", null); - - assertNotNull(cryptographyAsyncClient); - } - - private void pollOnKeyPurge(String keyName) { - int pendingPollCount = 0; - - while (pendingPollCount < 10) { - DeletedKey deletedKey = null; - - try { - deletedKey = keyAsyncClient.getDeletedKey(keyName).block(); - } catch (ResourceNotFoundException ignored) { - } - - if (deletedKey != null) { - sleepIfRunningAgainstService(2000); - - pendingPollCount += 1; - } else { - return; - } - } - - LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Key " + keyName + " was not purged"); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientBuilderTest.java deleted file mode 100644 index b8a933b60faf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientBuilderTest.java +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyClientBuilderTest { - private String vaultUrl; - private String keyName; - private KeyServiceVersion serviceVersion; - - @BeforeEach - public void setUp() { - vaultUrl = "https://key-vault-url.vault.azure.net/"; - keyName = "TestKey"; - serviceVersion = KeyServiceVersion.V7_3; - } - - @Test - public void buildSyncClientTest() { - KeyClient keyClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyClient); - assertEquals(KeyClient.class.getSimpleName(), keyClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - KeyClient keyClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyClient); - assertEquals(KeyClient.class.getSimpleName(), keyClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - KeyAsyncClient keyAsyncClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyAsyncClient); - assertEquals(KeyAsyncClient.class.getSimpleName(), keyAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - KeyAsyncClient keyAsyncClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyAsyncClient); - assertEquals(KeyAsyncClient.class.getSimpleName(), keyAsyncClient.getClass().getSimpleName()); - } - - @Test - public void emptyVaultUrlThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new KeyClientBuilder().vaultUrl("")); - } - - @Test - public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new KeyClientBuilder().credential(null)); - } - - @Test - public void clientOptionsIsPreferredOverLogOptions() { - KeyClient keyClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyClient.getKey(keyName)); - } - - @Test - public void applicationIdFallsBackToLogOptions() { - KeyClient keyClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyClient.getKey(keyName)); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - KeyClient keyClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyClient.getKey(keyName)); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new KeyClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .buildClient()); - } - - // This tests the policy is in the right place because if it were added per retry, it would be after the credentials - // and auth would fail because we changed a signed header. - @Test - public void addPerCallPolicy() { - KeyAsyncClient keyAsyncClient = new KeyClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - HttpPipeline pipeline = keyAsyncClient.getHttpPipeline(); - - int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; - - for (int i = 0; i < pipeline.getPolicyCount(); i++) { - if (pipeline.getPolicy(i).getClass() == RetryPolicy.class) { - retryPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerCallPolicy.class) { - perCallPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerRetryPolicy.class) { - perRetryPolicyPosition = i; - } - } - - assertTrue(perCallPolicyPosition != -1); - assertTrue(perCallPolicyPosition < retryPolicyPosition); - assertTrue(retryPolicyPosition < perRetryPolicyPosition); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTest.java deleted file mode 100644 index c625c21200c1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTest.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys; - -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.http.HttpClient; -import com.azure.core.test.TestMode; -import com.azure.core.util.Configuration; -import com.azure.security.keyvault.keys.models.KeyType; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.condition.EnabledIf; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.math.BigInteger; - -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@EnabledIf("shouldRunHsmTest") -public class KeyClientManagedHsmTest extends KeyClientTest implements KeyClientManagedHsmTestBase { - public KeyClientManagedHsmTest() { - this.isHsmEnabled = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; - this.runManagedHsmTest = shouldRunHsmTest(); - } - - public static boolean shouldRunHsmTest() { - return Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null - || TEST_MODE == TestMode.PLAYBACK; - } - - /** - * Tests that an RSA key is created. - */ - @Override - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - super.createRsaKey(httpClient, serviceVersion); - } - - /** - * Tests that an RSA key with a public exponent can be created in the key vault. - */ - @Override - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createRsaKeyWithPublicExponentRunner((keyToCreate) -> { - KeyVaultKey rsaKey = keyClient.createRsaKey(keyToCreate); - - assertKeyEquals(keyToCreate, rsaKey); - assertEquals(BigInteger.valueOf(keyToCreate.getPublicExponent()), toBigInteger(rsaKey.getKey().getE())); - assertEquals(keyToCreate.getKeySize(), rsaKey.getKey().getN().length * 8); - }); - } - - /** - * Tests that a symmetric key of a default is created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createOctKeyWithDefaultSize(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createOctKeyRunner(null, (keyToCreate) -> { - KeyVaultKey octKey = keyClient.createOctKey(keyToCreate); - - assertEquals(keyToCreate.getName(), octKey.getName()); - assertEquals(KeyType.OCT_HSM, octKey.getKey().getKeyType()); - assertEquals(keyToCreate.getExpiresOn(), octKey.getProperties().getExpiresOn()); - assertEquals(keyToCreate.getNotBefore(), octKey.getProperties().getNotBefore()); - assertEquals(keyToCreate.getTags(), octKey.getProperties().getTags()); - }); - } - - /** - * Tests that a symmetric key of a valid size is created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createOctKeyWithValidSize(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createOctKeyRunner(256, (keyToCreate) -> { - KeyVaultKey octKey = keyClient.createOctKey(keyToCreate); - - assertEquals(keyToCreate.getName(), octKey.getName()); - assertEquals(KeyType.OCT_HSM, octKey.getKey().getKeyType()); - assertEquals(keyToCreate.getExpiresOn(), octKey.getProperties().getExpiresOn()); - assertEquals(keyToCreate.getNotBefore(), octKey.getProperties().getNotBefore()); - assertEquals(keyToCreate.getTags(), octKey.getProperties().getTags()); - }); - } - - /** - * Tests that a symmetric key of an invalid size cannot be created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createOctKeyWithInvalidSize(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createOctKeyRunner(64, - (keyToCreate) -> assertThrows(ResourceModifiedException.class, () -> keyClient.createOctKey(keyToCreate))); - } - - /** - * Tests that random bytes can be retrieved from a Managed HSM. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getRandomBytes(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - getRandomBytesRunner((count) -> { - byte[] randomBytes = keyClient.getRandomBytes(count); - - assertEquals(count, randomBytes.length); - }); - } - - /** - * Tests that an existing key can be released. - */ - @Override - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Ignoring test until the service rolls out a fix for an issue with the "version" parameter of a release - // policy. - Assumptions.assumeTrue(serviceVersion != KeyServiceVersion.V7_4); - - super.releaseKey(httpClient, serviceVersion); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTestBase.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTestBase.java deleted file mode 100644 index 8f8e181e3ced..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientManagedHsmTestBase.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.http.HttpClient; -import org.junit.jupiter.api.Test; - -public interface KeyClientManagedHsmTestBase { - @Test - void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - void createOctKeyWithDefaultSize(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - void createOctKeyWithValidSize(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - void createOctKeyWithInvalidSize(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - void getRandomBytes(HttpClient httpClient, KeyServiceVersion serviceVersion); -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java deleted file mode 100644 index ad6462e9451e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java +++ /dev/null @@ -1,763 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpClient; -import com.azure.core.test.TestMode; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.keys.cryptography.CryptographyClient; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.keys.models.CreateKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.DeletedKey; -import com.azure.security.keyvault.keys.models.KeyProperties; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -import com.azure.security.keyvault.keys.models.KeyType; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import com.azure.security.keyvault.keys.models.ReleaseKeyResult; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.condition.DisabledIfSystemProperty; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.List; - -import static com.azure.security.keyvault.keys.TestUtils.buildSyncAssertingClient; -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyClientTest extends KeyClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(KeyClientTest.class); - - protected KeyClient keyClient; - - @Override - protected void beforeTest() { - beforeTestSetup(); - } - - protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion, null); - } - - protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) { - keyClient = getKeyClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - testTenantId, getEndpoint(), serviceVersion).buildClient(); - } - - /** - * Tests that a key can be created in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createKeyRunner((keyToCreate) -> { - KeyVaultKey createdKey = keyClient.createKey(keyToCreate); - - assertKeyEquals(keyToCreate, createdKey); - - if (!isHsmEnabled) { - assertEquals("0", createdKey.getProperties().getHsmPlatform()); - } - }); - } - - /** - * Tests that a key can be created in the key vault while using a different tenant ID than the one that will be - * provided in the authentication challenge. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); - - createKeyRunner((keyToCreate) -> assertKeyEquals(keyToCreate, keyClient.createKey(keyToCreate))); - - KeyVaultCredentialPolicy.clearCache(); // Ensure we don't have anything cached and try again. - - createKeyRunner((keyToCreate) -> assertKeyEquals(keyToCreate, keyClient.createKey(keyToCreate))); - } - - /** - * Tests that an RSA key is created. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createRsaKeyRunner((keyToCreate) -> assertKeyEquals(keyToCreate, keyClient.createRsaKey(keyToCreate))); - } - - /** - * Tests that an attempt to create a key with empty string name throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - KeyType keyType = runManagedHsmTest ? KeyType.RSA_HSM : KeyType.RSA; - assertRestException(() -> keyClient.createKey("", keyType), ResourceModifiedException.class, - HttpURLConnection.HTTP_BAD_REQUEST); - } - - /** - * Tests that we cannot create keys when key type is null. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createKeyEmptyValueRunner((keyToCreate) -> assertRestException( - () -> keyClient.createKey(keyToCreate.getName(), keyToCreate.getKeyType()), ResourceModifiedException.class, - HttpURLConnection.HTTP_BAD_REQUEST)); - } - - /** - * Verifies that an exception is thrown when null key object is passed for creation. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - assertThrows(NullPointerException.class, () -> keyClient.createKey(null)); - } - - /** - * Tests that a key is able to be updated when it exists. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - updateKeyRunner((originalKeyOptions, updatedKeyOptions) -> { - KeyVaultKey createdKey = keyClient.createKey(originalKeyOptions); - - assertKeyEquals(originalKeyOptions, createdKey); - - KeyVaultKey updatedKey = keyClient - .updateKeyProperties(createdKey.getProperties().setExpiresOn(updatedKeyOptions.getExpiresOn())); - - assertKeyEquals(updatedKeyOptions, updatedKey); - }); - } - - /** - * Tests that a key can be updated when it is disabled. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - updateDisabledKeyRunner((createKeyOptions, updateKeyOptions) -> { - KeyVaultKey createdKey = keyClient.createKey(createKeyOptions); - - assertKeyEquals(createKeyOptions, createdKey); - - KeyVaultKey updatedKey = keyClient - .updateKeyProperties(createdKey.getProperties().setExpiresOn(updateKeyOptions.getExpiresOn())); - - assertKeyEquals(updateKeyOptions, updatedKey); - }); - } - - /** - * Tests that an existing key can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - getKeyRunner((keyToSetAndGet) -> { - keyClient.createKey(keyToSetAndGet); - - KeyVaultKey retrievedKey = keyClient.getKey(keyToSetAndGet.getName()); - - assertKeyEquals(keyToSetAndGet, retrievedKey); - - if (!isHsmEnabled) { - assertEquals("0", retrievedKey.getProperties().getHsmPlatform()); - } - }); - } - - /** - * Tests that a specific version of the key can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - getKeySpecificVersionRunner((keyWithOriginalValue, keyWithNewValue) -> { - KeyVaultKey keyVersionOne = keyClient.createKey(keyWithOriginalValue); - KeyVaultKey keyVersionTwo = keyClient.createKey(keyWithNewValue); - - assertKeyEquals(keyWithOriginalValue, - keyClient.getKey(keyVersionOne.getName(), keyVersionOne.getProperties().getVersion())); - assertKeyEquals(keyWithNewValue, - keyClient.getKey(keyVersionTwo.getName(), keyVersionTwo.getProperties().getVersion())); - }); - } - - /** - * Tests that an attempt to get a non-existing key throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - assertRestException(() -> keyClient.getKey("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that an existing key can be deleted. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - deleteKeyRunner((keyToDelete) -> { - sleepIfRunningAgainstService(30000); - - assertKeyEquals(keyToDelete, keyClient.createKey(keyToDelete)); - - SyncPoller deletedKeyPoller - = setPlaybackSyncPollerPollInterval(keyClient.beginDeleteKey(keyToDelete.getName())); - - DeletedKey deletedKey = deletedKeyPoller.waitForCompletion().getValue(); - - assertNotNull(deletedKey.getDeletedOn()); - assertNotNull(deletedKey.getRecoveryId()); - assertNotNull(deletedKey.getScheduledPurgeDate()); - assertEquals(keyToDelete.getName(), deletedKey.getName()); - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - assertRestException(() -> keyClient.beginDeleteKey("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that an attempt to retrieve a non-existing deleted key throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - assertRestException(() -> keyClient.getDeletedKey("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that a deleted key can be recovered on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { - assertKeyEquals(keyToDeleteAndRecover, keyClient.createKey(keyToDeleteAndRecover)); - - SyncPoller poller - = setPlaybackSyncPollerPollInterval(keyClient.beginDeleteKey(keyToDeleteAndRecover.getName())); - - assertNotNull(poller.waitForCompletion()); - - SyncPoller recoverPoller - = setPlaybackSyncPollerPollInterval(keyClient.beginRecoverDeletedKey(keyToDeleteAndRecover.getName())); - - KeyVaultKey recoveredKey = recoverPoller.waitForCompletion().getValue(); - - assertEquals(keyToDeleteAndRecover.getName(), recoveredKey.getName()); - assertEquals(keyToDeleteAndRecover.getNotBefore(), recoveredKey.getProperties().getNotBefore()); - assertEquals(keyToDeleteAndRecover.getExpiresOn(), recoveredKey.getProperties().getExpiresOn()); - }); - } - - /** - * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - assertRestException(() -> keyClient.beginRecoverDeletedKey("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that a key can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - backupKeyRunner((keyToBackup) -> { - assertKeyEquals(keyToBackup, keyClient.createKey(keyToBackup)); - - byte[] backupBytes = (keyClient.backupKey(keyToBackup.getName())); - - assertNotNull(backupBytes); - assertTrue(backupBytes.length > 0); - }); - } - - /** - * Tests that an attempt to back up a non-existing key throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - assertRestException(() -> keyClient.backupKey("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that a key can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - restoreKeyRunner((keyToBackupAndRestore) -> { - assertKeyEquals(keyToBackupAndRestore, keyClient.createKey(keyToBackupAndRestore)); - - byte[] backupBytes = (keyClient.backupKey(keyToBackupAndRestore.getName())); - - assertNotNull(backupBytes); - assertTrue(backupBytes.length > 0); - - SyncPoller poller - = setPlaybackSyncPollerPollInterval(keyClient.beginDeleteKey(keyToBackupAndRestore.getName())); - - poller.waitForCompletion(); - - keyClient.purgeDeletedKey(keyToBackupAndRestore.getName()); - - pollOnKeyPurge(keyToBackupAndRestore.getName()); - sleepIfRunningAgainstService(60000); - - KeyVaultKey restoredKey = keyClient.restoreKeyBackup(backupBytes); - - assertEquals(keyToBackupAndRestore.getName(), restoredKey.getName()); - assertEquals(keyToBackupAndRestore.getExpiresOn(), restoredKey.getProperties().getExpiresOn()); - }); - } - - /** - * Tests that an attempt to restore a key from malformed backup bytes throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - byte[] keyBackupBytes = "non-existing".getBytes(); - - assertRestException(() -> keyClient.restoreKeyBackup(keyBackupBytes), ResourceModifiedException.class, - HttpURLConnection.HTTP_BAD_REQUEST); - } - - /** - * Tests that keys can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - listKeysRunner((keysToList) -> { - - for (CreateKeyOptions key : keysToList.values()) { - assertKeyEquals(key, keyClient.createKey(key)); - } - - sleepIfRunningAgainstService(5000); - - for (KeyProperties actualKey : keyClient.listPropertiesOfKeys()) { - if (keysToList.containsKey(actualKey.getName())) { - CreateKeyOptions expectedKey = keysToList.get(actualKey.getName()); - - assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); - assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); - - keysToList.remove(actualKey.getName()); - } - } - assertEquals(0, keysToList.size()); - }); - } - - /** - * Tests that a deleted key can be retrieved on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - getDeletedKeyRunner((keyToDeleteAndGet) -> { - assertKeyEquals(keyToDeleteAndGet, keyClient.createKey(keyToDeleteAndGet)); - - SyncPoller poller - = setPlaybackSyncPollerPollInterval(keyClient.beginDeleteKey(keyToDeleteAndGet.getName())); - - poller.waitForCompletion(); - - sleepIfRunningAgainstService(30000); - - DeletedKey deletedKey = keyClient.getDeletedKey(keyToDeleteAndGet.getName()); - - assertNotNull(deletedKey.getDeletedOn()); - assertNotNull(deletedKey.getRecoveryId()); - assertNotNull(deletedKey.getScheduledPurgeDate()); - assertEquals(keyToDeleteAndGet.getName(), deletedKey.getName()); - }); - } - - /** - * Tests that deleted keys can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - // Skip when running against the service to avoid having pipeline runs take longer than they have to. - if (interceptorManager.isLiveMode()) { - return; - } - - listDeletedKeysRunner((keysToList) -> { - for (CreateKeyOptions key : keysToList.values()) { - assertKeyEquals(key, keyClient.createKey(key)); - } - - for (CreateKeyOptions key : keysToList.values()) { - SyncPoller poller - = setPlaybackSyncPollerPollInterval(keyClient.beginDeleteKey(key.getName())); - - poller.waitForCompletion(); - } - - sleepIfRunningAgainstService(90000); - - Iterable deletedKeys = keyClient.listDeletedKeys(); - - for (DeletedKey deletedKey : deletedKeys) { - assertNotNull(deletedKey.getDeletedOn()); - assertNotNull(deletedKey.getRecoveryId()); - } - }); - } - - /** - * Tests that key versions can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - listKeyVersionsRunner((keysToList) -> { - String keyName = null; - - for (CreateKeyOptions key : keysToList) { - keyName = key.getName(); - - sleepIfRunningAgainstService(4000); - - assertKeyEquals(key, keyClient.createKey(key)); - } - - Iterable keyVersionsOutput = keyClient.listPropertiesOfKeyVersions(keyName); - List keyVersionsList = new ArrayList<>(); - - keyVersionsOutput.forEach(keyVersionsList::add); - - assertEquals(keysToList.size(), keyVersionsList.size()); - }); - } - - /** - * Tests that an existing key can be released. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // TODO: Remove assumption once Key Vault allows for creating exportable keys. - Assumptions.assumeTrue(runManagedHsmTest && runReleaseKeyTest); - - createKeyClient(httpClient, serviceVersion); - - releaseKeyRunner((keyToRelease, attestationUrl) -> { - assertKeyEquals(keyToRelease, keyClient.createRsaKey(keyToRelease)); - - String targetAttestationToken = "testAttestationToken"; - - if (getTestMode() != TestMode.PLAYBACK) { - if (!attestationUrl.endsWith("/")) { - attestationUrl = attestationUrl + "/"; - } - - targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token"); - } - - ReleaseKeyResult releaseKeyResult = keyClient.releaseKey(keyToRelease.getName(), targetAttestationToken); - - assertNotNull(releaseKeyResult.getValue()); - }); - } - - /** - * Tests that fetching the key rotation policy of a non-existent key throws. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyClient(httpClient, serviceVersion); - - String keyName = testResourceNamer.randomName("nonExistentKey", 20); - - assertThrows(ResourceNotFoundException.class, () -> keyClient.getKeyRotationPolicy(keyName)); - } - - /** - * Tests that fetching the key rotation policy of a non-existent key throws. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyClient(httpClient, serviceVersion); - - String keyName = testResourceNamer.randomName("rotateKey", 20); - - keyClient.createRsaKey(new CreateRsaKeyOptions(keyName)); - - KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy(keyName); - - assertNotNull(keyRotationPolicy); - assertNull(keyRotationPolicy.getId()); - assertNull(keyRotationPolicy.getCreatedOn()); - assertNull(keyRotationPolicy.getUpdatedOn()); - assertNull(keyRotationPolicy.getExpiresIn()); - assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); - assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction()); - assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); - assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); - } - - /** - * Tests that fetching the key rotation policy of a non-existent key throws. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @Disabled("Disable after https://github.com/Azure/azure-sdk-for-java/issues/31510 is fixed.") - //@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, - KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyClient(httpClient, serviceVersion); - - updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> { - keyClient.createRsaKey(new CreateRsaKeyOptions(keyName)); - - KeyRotationPolicy updatedKeyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicy); - KeyRotationPolicy retrievedKeyRotationPolicy = keyClient.getKeyRotationPolicy(keyName); - - assertKeyVaultRotationPolicyEquals(updatedKeyRotationPolicy, retrievedKeyRotationPolicy); - }); - } - - /** - * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyClient(httpClient, serviceVersion); - - updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> { - keyClient.createRsaKey(new CreateRsaKeyOptions(keyName)); - - KeyRotationPolicy updatedKeyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicy); - KeyRotationPolicy retrievedKeyRotationPolicy = keyClient.getKeyRotationPolicy(keyName); - - assertKeyVaultRotationPolicyEquals(updatedKeyRotationPolicy, retrievedKeyRotationPolicy); - }); - } - - /** - * Tests that a key can be rotated. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") - public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { - // Key Rotation is not yet enabled in Managed HSM. - Assumptions.assumeTrue(!isHsmEnabled); - - createKeyClient(httpClient, serviceVersion); - - String keyName = testResourceNamer.randomName("rotateKey", 20); - KeyVaultKey createdKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName)); - KeyVaultKey rotatedKey = keyClient.rotateKey(keyName); - - assertEquals(createdKey.getName(), rotatedKey.getName()); - assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); - } - - /** - * Tests that a {@link CryptographyClient} can be created for a given key and version using a {@link KeyClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - CryptographyClient cryptographyClient = keyClient.getCryptographyClient("myKey"); - - assertNotNull(cryptographyClient); - } - - /** - * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests - * that cryptographic operations can be performed with said cryptography client. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - createKeyRunner((keyToCreate) -> { - assertKeyEquals(keyToCreate, keyClient.createKey(keyToCreate)); - - CryptographyClient cryptographyClient = keyClient.getCryptographyClient(keyToCreate.getName()); - - assertNotNull(cryptographyClient); - - byte[] plaintext = "myPlaintext".getBytes(); - byte[] ciphertext = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext).getCipherText(); - byte[] decryptedText = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext).getPlainText(); - - assertArrayEquals(plaintext, decryptedText); - }); - } - - /** - * Tests that a {@link CryptographyClient} can be created for a given key and version using a {@link KeyClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - CryptographyClient cryptographyClient - = keyClient.getCryptographyClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); - - assertNotNull(cryptographyClient); - } - - /** - * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - CryptographyClient cryptographyClient = keyClient.getCryptographyClient("myKey", ""); - - assertNotNull(cryptographyClient); - } - - /** - * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getCryptographyClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { - createKeyClient(httpClient, serviceVersion); - - CryptographyClient cryptographyClient = keyClient.getCryptographyClient("myKey", null); - - assertNotNull(cryptographyClient); - } - - private void pollOnKeyPurge(String keyName) { - int pendingPollCount = 0; - - while (pendingPollCount < 10) { - DeletedKey deletedKey = null; - - try { - deletedKey = keyClient.getDeletedKey(keyName); - } catch (ResourceNotFoundException ignored) { - } - - if (deletedKey != null) { - sleepIfRunningAgainstService(2000); - - pendingPollCount += 1; - } else { - return; - } - } - - LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Key " + keyName + " was not purged"); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java deleted file mode 100644 index 1a5abe8b10ed..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java +++ /dev/null @@ -1,679 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpMethod; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.test.TestMode; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.BodilessMatcher; -import com.azure.core.test.models.CustomMatcher; -import com.azure.core.test.models.TestProxyRequestMatcher; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.identity.AzurePowerShellCredentialBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -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.KeyReleasePolicy; -import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; -import com.azure.security.keyvault.keys.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; -import com.azure.security.keyvault.keys.models.KeyType; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.provider.Arguments; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.math.BigInteger; -import java.time.Duration; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public abstract class KeyClientTestBase extends TestProxyTestBase { - private static final String KEY_NAME = "javaKeyTemp"; - private static final String AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS"; - private static final String SERVICE_VERSION_FROM_ENV - = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS); - - private static final int MAX_RETRIES = 5; - private static final RetryOptions LIVE_RETRY_OPTIONS - = new RetryOptions(new ExponentialBackoffOptions().setMaxRetries(MAX_RETRIES) - .setBaseDelay(Duration.ofSeconds(2)) - .setMaxDelay(Duration.ofSeconds(16))); - - private static final ClientLogger LOGGER = new ClientLogger(KeyClientTestBase.class); - - public static final TestMode TEST_MODE = initializeTestMode(); - - private static final RetryOptions PLAYBACK_RETRY_OPTIONS - = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); - - protected boolean isHsmEnabled = false; - protected boolean runManagedHsmTest = false; - protected boolean runReleaseKeyTest = false; - // TODO (vcolin7): Un-comment after the service rolls out a fix for the version issue (late Nov 2023). - //protected boolean runReleaseKeyTest = getTestMode() == TestMode.PLAYBACK - // || Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ATTESTATION_URL") != null; - - private static TestMode initializeTestMode() { - final String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); - - if (azureTestMode != null) { - try { - return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); - } catch (IllegalArgumentException e) { - LOGGER.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); - return TestMode.PLAYBACK; - } - } - - LOGGER.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); - return TestMode.PLAYBACK; - } - - void beforeTestSetup() { - System.getProperties() - .put("IS_SKIP_ROTATION_POLICY_TEST", - String.valueOf(!".vault.azure.net" - .equals(Configuration.getGlobalConfiguration().get("KEY_VAULT_ENDPOINT_SUFFIX", ".vault.azure.net")) - && interceptorManager.isLiveMode())); - - KeyVaultCredentialPolicy.clearCache(); - } - - KeyClientBuilder getKeyClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, - KeyServiceVersion serviceVersion) { - TokenCredential credential; - - if (interceptorManager.isLiveMode()) { - credential = new AzurePowerShellCredentialBuilder().build(); - } else if (interceptorManager.isRecordMode()) { - credential = new DefaultAzureCredentialBuilder().build(); - } else { - credential = new MockTokenCredential(); - - List customMatchers = new ArrayList<>(); - customMatchers.add(new BodilessMatcher()); - customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); - interceptorManager.addMatchers(customMatchers); - } - - KeyClientBuilder builder = new KeyClientBuilder().vaultUrl(endpoint) - .serviceVersion(serviceVersion) - .credential(credential) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - return interceptorManager.isRecordMode() - ? builder.addPolicy(interceptorManager.getRecordPolicy()) - : builder; - } - } - - @Test - public abstract void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void createKeyRunner(Consumer testRunner) { - final Map tags = new HashMap<>(); - - tags.put("foo", "baz"); - - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToCreate = new CreateKeyOptions(testResourceNamer.randomName(KEY_NAME, 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) - .setTags(tags); - - testRunner.accept(keyToCreate); - } - - @Test - public abstract void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void createRsaKeyRunner(Consumer testRunner) { - final Map tags = Collections.singletonMap("foo", "baz"); - - final CreateRsaKeyOptions keyToCreate = new CreateRsaKeyOptions(testResourceNamer.randomName(KEY_NAME, 20)) - .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) - .setTags(tags); - - if (runManagedHsmTest) { - keyToCreate.setHardwareProtected(true); - } - - testRunner.accept(keyToCreate); - } - - @Test - public abstract void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void createKeyEmptyValueRunner(Consumer testRunner) { - CreateKeyOptions keyToCreate = new CreateKeyOptions(KEY_NAME, null); - - testRunner.accept(keyToCreate); - } - - @Test - public abstract void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void updateKeyRunner(BiConsumer testRunner) { - final Map tags = new HashMap<>(); - - tags.put("first tag", "first value"); - tags.put("second tag", "second value"); - - final String keyName = testResourceNamer.randomName("testKey1", 20); - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions originalKey = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setTags(tags); - final CreateKeyOptions updatedKey = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setTags(tags); - - testRunner.accept(originalKey, updatedKey); - } - - @Test - public abstract void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void updateDisabledKeyRunner(BiConsumer testRunner) { - final String keyName = testResourceNamer.randomName("testKey2", 20); - final KeyType keyType = isHsmEnabled ? KeyType.EC_HSM : KeyType.EC; - final CreateKeyOptions originalKey = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setEnabled(false); - final CreateKeyOptions updatedKey = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(originalKey, updatedKey); - } - - @Test - public abstract void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void getKeyRunner(Consumer testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToSetAndGet - = new CreateKeyOptions(testResourceNamer.randomName("testKey4", 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyToSetAndGet); - } - - @Test - public abstract void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void getKeySpecificVersionRunner(BiConsumer testRunner) { - final String keyName = testResourceNamer.randomName("testKey3", 20); - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyWithOriginalValue = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - final CreateKeyOptions keyWithNewValue = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyWithOriginalValue, keyWithNewValue); - } - - @Test - public abstract void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void deleteKeyRunner(Consumer testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToDelete = new CreateKeyOptions(testResourceNamer.randomName("testKey5", 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyToDelete); - } - - @Test - public abstract void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void getDeletedKeyRunner(Consumer testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToDeleteAndGet - = new CreateKeyOptions(testResourceNamer.randomName("testKey6", 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyToDeleteAndGet); - } - - @Test - public abstract void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void recoverDeletedKeyRunner(Consumer testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToDeleteAndRecover - = new CreateKeyOptions(testResourceNamer.randomName("testKey7", 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyToDeleteAndRecover); - } - - @Test - public abstract void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void backupKeyRunner(Consumer testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToBackup = new CreateKeyOptions(testResourceNamer.randomName("testKey8", 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyToBackup); - } - - @Test - public abstract void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void restoreKeyRunner(Consumer testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - final CreateKeyOptions keyToBackupAndRestore - = new CreateKeyOptions(testResourceNamer.randomName("testKey9", 20), keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - testRunner.accept(keyToBackupAndRestore); - } - - @Test - public abstract void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void listKeysRunner(Consumer> testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - HashMap keysToList = new HashMap<>(); - String keyName; - - for (int i = 0; i < 2; i++) { - keyName = testResourceNamer.randomName("listKey" + i, 20); - CreateKeyOptions key = new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); - - keysToList.put(keyName, key); - } - - testRunner.accept(keysToList); - } - - @Test - public abstract void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void listKeyVersionsRunner(Consumer> testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - List keysToList = new ArrayList<>(); - String keyName = testResourceNamer.randomName("listKeyVersion", 20); - - for (int i = 1; i < 5; i++) { - keysToList.add(new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC))); - } - - testRunner.accept(keysToList); - } - - @Test - public abstract void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void listDeletedKeysRunner(Consumer> testRunner) { - final KeyType keyType = isHsmEnabled ? KeyType.RSA_HSM : KeyType.RSA; - HashMap keysToList = new HashMap<>(); - String keyName; - - for (int i = 0; i < 3; i++) { - keyName = testResourceNamer.randomName("listDeletedKeysTest" + i, 20); - - keysToList.put(keyName, new CreateKeyOptions(keyName, keyType) - .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - } - - testRunner.accept(keysToList); - } - - void createRsaKeyWithPublicExponentRunner(Consumer testRunner) { - final Map tags = new HashMap<>(); - - tags.put("foo", "baz"); - - final CreateRsaKeyOptions keyToCreate = new CreateRsaKeyOptions(testResourceNamer.randomName("testRsaKey", 20)) - .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) - .setTags(tags) - .setKeySize(2048) - .setPublicExponent(3); - - if (runManagedHsmTest) { - keyToCreate.setHardwareProtected(true); - } - - testRunner.accept(keyToCreate); - } - - void createOctKeyRunner(Integer keySize, Consumer testRunner) { - final Map tags = new HashMap<>(); - - tags.put("foo", "baz"); - - final CreateOctKeyOptions keyToCreate = new CreateOctKeyOptions(testResourceNamer.randomName("testOctKey", 20)) - .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) - .setKeySize(keySize) - .setTags(tags); - - if (runManagedHsmTest) { - keyToCreate.setHardwareProtected(true); - } - - testRunner.accept(keyToCreate); - } - - void getRandomBytesRunner(Consumer testRunner) { - int count = 12; - - testRunner.accept(count); - } - - @Test - public abstract void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - void releaseKeyRunner(BiConsumer testRunner) { - final String attestationUrl - = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ATTESTATION_URL", "https://localhost:8080"); - final String releasePolicyContents = "{" + "\"anyOf\": [" + "{" + "\"allOf\": [" + "{" - + "\"claim\": \"sdk-test\"," + "\"equals\": \"true\"" + "}" + "]," + "\"authority\": \"" + attestationUrl - + "\"" + "}" + "]," + "\"version\": \"1.0.0\"" + "}"; - - final CreateRsaKeyOptions keyToRelease - = new CreateRsaKeyOptions(testResourceNamer.randomName("keyToRelease", 20)).setKeySize(2048) - .setHardwareProtected(runManagedHsmTest) - .setReleasePolicy(new KeyReleasePolicy(BinaryData.fromString(releasePolicyContents))) - .setExportable(true); - - testRunner.accept(keyToRelease, attestationUrl); - } - - @Test - public abstract void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion); - - @Test - public abstract void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, - KeyServiceVersion serviceVersion); - - void updateGetKeyRotationPolicyWithMinimumPropertiesRunner(BiConsumer testRunner) { - String keyName = testResourceNamer.randomName("rotateKey", 20); - - KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy().setLifetimeActions(Collections.emptyList()); - - testRunner.accept(keyName, keyRotationPolicy); - } - - @Test - public abstract void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, - KeyServiceVersion serviceVersion); - - void updateGetKeyRotationPolicyWithAllPropertiesRunner(BiConsumer testRunner) { - String keyName = testResourceNamer.randomName("rotateKey", 20); - - List keyRotationLifetimeActionList = new ArrayList<>(); - KeyRotationLifetimeAction rotateLifetimeAction - = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE).setTimeAfterCreate("P7D"); - KeyRotationLifetimeAction notifyLifetimeAction - = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY).setTimeBeforeExpiry("P7D"); - - keyRotationLifetimeActionList.add(rotateLifetimeAction); - keyRotationLifetimeActionList.add(notifyLifetimeAction); - - KeyRotationPolicy keyRotationPolicy - = new KeyRotationPolicy().setLifetimeActions(keyRotationLifetimeActionList).setExpiresIn("P6M"); - - testRunner.accept(keyName, keyRotationPolicy); - } - - @Test - public abstract void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion); - - /** - * Helper method to verify that the returned ConfigurationSetting matches what was expected. - * - * @param expected ConfigurationSetting expected to be returned by the service. - * @param actual ConfigurationSetting contained in the RestResponse body. - */ - static void assertKeyEquals(CreateKeyOptions expected, KeyVaultKey actual) { - assertEquals(expected.getName(), actual.getName()); - assertEquals(expected.getKeyType(), actual.getKey().getKeyType()); - assertEquals(expected.getExpiresOn(), actual.getProperties().getExpiresOn()); - assertEquals(expected.getNotBefore(), actual.getProperties().getNotBefore()); - assertEquals(expected.getTags(), actual.getProperties().getTags()); - } - - public String getEndpoint() { - final String endpoint = isHsmEnabled - ? Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT", "https://localhost:8080") - : Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https://localhost:8080"); - - Objects.requireNonNull(endpoint); - - return endpoint; - } - - static void assertRestException(Runnable exceptionThrower, - Class expectedExceptionType, int expectedStatusCode) { - HttpResponseException ex = assertThrows(expectedExceptionType, exceptionThrower::run); - assertEquals(expectedStatusCode, ex.getResponse().getStatusCode()); - } - - static void assertRestException(Throwable exception, Class expectedExceptionType, - int expectedStatusCode) { - assertEquals(expectedExceptionType, exception.getClass()); - assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); - } - - /** - * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and - * service versions that should be tested. - * - * @return A stream of HttpClient and service version combinations to test. - */ - static Stream getTestParameters() { - // When this issues is closed, the newer version of junit will have better support for cartesian product of - // arguments - https://github.com/junit-team/junit5/issues/1427 - List argumentsList = new ArrayList<>(); - - getHttpClients().forEach(httpClient -> { - Arrays.stream(KeyServiceVersion.values()) - .filter(KeyClientTestBase::shouldServiceVersionBeTested) - .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); - }); - - return argumentsList.stream(); - } - - /** - * Returns whether the given service version match the rules of test framework. - * - *
    - *
  • Using latest service version as default if no environment variable is set.
  • - *
  • If it's set to ALL, all Service versions in {@link KeyServiceVersion} will be tested.
  • - *
  • Otherwise, Service version string should match env variable.
  • - *
- * - * Environment values currently supported are: "ALL", "${version}". - * Use comma to separate http clients want to test. - * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} - * - * @param serviceVersion ServiceVersion needs to check. - * - * @return Boolean indicates whether filters out the service version or not. - */ - private static boolean shouldServiceVersionBeTested(KeyServiceVersion serviceVersion) { - if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { - return KeyServiceVersion.getLatest().equals(serviceVersion); - } - - if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { - return true; - } - - String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); - - return Arrays.stream(configuredServiceVersionList) - .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); - } - - protected static BigInteger toBigInteger(byte[] b) { - if (b[0] < 0) { - // RSA parameters are always positive numbers, so if the first byte - // is negative, we need to add a leading zero - // to make the entire BigInteger positive. - byte[] temp = new byte[1 + b.length]; - System.arraycopy(b, 0, temp, 1, b.length); - b = temp; - } - - return new BigInteger(b); - } - - public static class AttestationToken implements JsonSerializable { - String token; - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject().writeStringField("token", token).writeEndObject(); - } - - public static AttestationToken fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - AttestationToken token = new AttestationToken(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("token".equals(fieldName)) { - token.token = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return token; - }); - } - } - - public static String getAttestationToken(String attestationUrl) { - HttpClient attestationClient = HttpClient.createDefault(); - - return attestationClient.send(new HttpRequest(HttpMethod.GET, attestationUrl)) - .flatMap(HttpResponse::getBodyAsByteArray) - .flatMap(bytes -> Mono.fromCallable(() -> { - try (JsonReader jsonReader = JsonProviders.createReader(bytes)) { - return AttestationToken.fromJson(jsonReader).getToken(); - } - })) - .block(); - } - - protected void assertKeyVaultRotationPolicyEquals(KeyRotationPolicy expected, KeyRotationPolicy actual) { - assertTrue(expected == null && actual == null || expected != null && actual != null); - - if (expected == null) { - return; - } - - assertEquals(expected.getId(), actual.getId()); - assertEquals(expected.getCreatedOn(), actual.getCreatedOn()); - assertEquals(expected.getUpdatedOn(), actual.getUpdatedOn()); - assertEquals(expected.getExpiresIn(), actual.getExpiresIn()); - - List expectedLifetimeActions = expected.getLifetimeActions(); - List actualLifetimeActions = actual.getLifetimeActions(); - - assertTrue(expectedLifetimeActions == null && actualLifetimeActions == null - || expectedLifetimeActions != null && actualLifetimeActions != null); - - if (expectedLifetimeActions != null) { - assertEquals(expectedLifetimeActions.size(), actualLifetimeActions.size()); - - for (int i = 0; i < expectedLifetimeActions.size(); i++) { - KeyRotationLifetimeAction expectedLifetimeAction = expectedLifetimeActions.get(i); - KeyRotationLifetimeAction actualLifetimeAction = actualLifetimeActions.get(i); - - assertEquals(expectedLifetimeAction.getAction(), actualLifetimeAction.getAction()); - assertEquals(expectedLifetimeAction.getTimeAfterCreate(), actualLifetimeAction.getTimeAfterCreate()); - assertEquals(expectedLifetimeAction.getTimeBeforeExpiry(), actualLifetimeAction.getTimeBeforeExpiry()); - } - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java deleted file mode 100644 index 9ff7d06b868d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.credential.AccessToken; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.test.SyncAsyncExtension; -import com.azure.core.test.annotation.SyncAsyncTest; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.Base64Util; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; -import java.util.stream.Stream; - -import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; -import static com.azure.core.util.CoreUtils.isNullOrEmpty; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.SAME_THREAD) -public class KeyVaultCredentialPolicyTest { - private static final String AUTHENTICATE_HEADER - = "Bearer authorization=\"https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd022db57\", " - + "resource=\"https://vault.azure.net\""; - private static final String AUTHENTICATE_HEADER_WITH_CLAIMS - = "Bearer realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", " - + "error=\"insufficient_claims\", " - + "claims=\"eyJhY2Nlc3NfdG9rZW4iOnsiYWNycyI6eyJlc3NlbnRpYWwiOnRydWUsInZhbHVlIjoiY3AxIn19fQ==\""; - private static final String DECODED_CLAIMS = "{\"access_token\":{\"acrs\":{\"essential\":true,\"value\":\"cp1\"}}}"; - private static final String BEARER = "Bearer"; - private static final String BODY = "this is a sample body"; - private static final Flux BODY_FLUX = Flux.defer( - () -> Flux.fromStream(Stream.of(BODY.split("")).map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))))); - private static final String FAKE_ENCODED_CREDENTIAL - = Base64Util.encodeToString("user:fakePasswordPlaceholder".getBytes(StandardCharsets.UTF_8)); - private static final List> BASE_ASSERTIONS = Arrays.asList( - tokenRequestContext -> !tokenRequestContext.getScopes().isEmpty(), - tokenRequestContext -> !isNullOrEmpty(tokenRequestContext.getTenantId()), TokenRequestContext::isCaeEnabled); - - private HttpResponse simpleResponse; - private HttpResponse unauthorizedHttpResponseWithWrongStatusCode; - private HttpResponse unauthorizedHttpResponseWithHeader; - private HttpResponse unauthorizedHttpResponseWithoutHeader; - private HttpResponse unauthorizedHttpResponseWithHeaderAndClaims; - private HttpPipelineCallContext callContext; - private HttpPipelineCallContext differentScopeContext; - private HttpPipelineCallContext testContext; - private HttpPipelineCallContext bodyContext; - private HttpPipelineCallContext bodyFluxContext; - private TokenCredential credential; - - private static HttpPipelineCallContext createCallContext(HttpRequest request, Context context) { - AtomicReference callContextReference = new AtomicReference<>(); - - HttpPipeline callContextCreator = new HttpPipelineBuilder().policies((callContext, next) -> { - callContextReference.set(callContext); - - return next.process(); - }).httpClient(ignored -> Mono.empty()).build(); - - callContextCreator.sendSync(request, context); - - return callContextReference.get(); - } - - @BeforeEach - public void setup() { - HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net"); - HttpRequest requestWithDifferentScope = new HttpRequest(HttpMethod.GET, "https://mytest.azurecr.io"); - - Context bodyContextContext = new Context("KeyVaultCredentialPolicyStashedBody", BinaryData.fromString(BODY)) - .addData("KeyVaultCredentialPolicyStashedContentLength", "21"); - - Context bodyFluxContextContext = new Context("KeyVaultCredentialPolicyStashedBody", BODY_FLUX) - .addData("KeyVaultCredentialPolicyStashedContentLength", "21"); - - MockHttpResponse simpleResponse - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 200); - - MockHttpResponse unauthorizedResponseWithWrongStatusCode - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 500); - - MockHttpResponse unauthorizedResponseWithoutHeader - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401); - - MockHttpResponse unauthorizedResponseWithHeader - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401, - new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, AUTHENTICATE_HEADER)); - - MockHttpResponse unauthorizedResponseWithHeaderAndClaims - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401, - new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, AUTHENTICATE_HEADER_WITH_CLAIMS)); - - this.simpleResponse = simpleResponse; - this.unauthorizedHttpResponseWithWrongStatusCode = unauthorizedResponseWithWrongStatusCode; - this.unauthorizedHttpResponseWithHeader = unauthorizedResponseWithHeader; - this.unauthorizedHttpResponseWithoutHeader = unauthorizedResponseWithoutHeader; - this.unauthorizedHttpResponseWithHeaderAndClaims = unauthorizedResponseWithHeaderAndClaims; - this.callContext = createCallContext(request, Context.NONE); - this.differentScopeContext = createCallContext(requestWithDifferentScope, Context.NONE); - this.testContext = createCallContext(request, Context.NONE); - this.bodyContext = createCallContext(request, bodyContextContext); - this.bodyFluxContext = createCallContext(request, bodyFluxContextContext); - // Can't use BasicAuthenticationCredential until the following PR is merged: - // https://github.com/Azure/azure-sdk-for-java/pull/42238 - this.credential = tokenRequestContext -> Mono - .fromCallable(() -> new AccessToken(FAKE_ENCODED_CREDENTIAL, OffsetDateTime.MAX.minusYears(1))); - } - - @AfterEach - public void cleanup() { - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onNon401ErrorResponse() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(unauthorizedHttpResponseWithWrongStatusCode)) - .build(); - - SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - assertNull(this.callContext.getHttpRequest().getHeaders().get(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void on401UnauthorizedResponseWithHeader() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(unauthorizedHttpResponseWithHeader)) - .build(); - - SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - assertNotNull(this.callContext.getHttpRequest().getHeaders().get(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onChallengeCredentialPolicy() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.callContext, this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.callContext, this.unauthorizedHttpResponseWithHeader)); - - // Validate that the onChallengeSync ran successfully. - assertTrue(onChallenge); - - String tokenValue = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresent() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - StepVerifier.create(onChallengeAndClearCache(policy, this.callContext, unauthorizedHttpResponseWithHeader) // Challenge cache created - .then(policy.authorizeRequest(this.testContext))) // Challenge cache used - .verifyComplete(); - - String tokenValue = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentSync() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // Challenge cache created - onChallengeAndClearCacheSync(policy, this.callContext, unauthorizedHttpResponseWithHeader); - // Challenge cache used - policy.authorizeRequestSync(this.testContext); - - String tokenValue = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentWithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - StepVerifier.create(policy.authorizeRequestOnChallenge(this.callContext, // Challenge cache created - this.unauthorizedHttpResponseWithHeader).flatMap(authorized -> { - if (authorized) { - String firstToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(firstToken.isEmpty()); - assertTrue(firstToken.startsWith(BEARER)); - - testCredential.replaceAssertion( - tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), 3); - - return policy.authorizeRequestOnChallenge(this.callContext, // Challenge with claims received - this.unauthorizedHttpResponseWithHeaderAndClaims).map(ignored -> firstToken); - } else { - return Mono.just(""); - } - })).assertNext(firstToken -> { - String newToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(newToken.isEmpty()); - assertTrue(newToken.startsWith(BEARER)); - - assertNotEquals(firstToken, newToken); - }).verifyComplete(); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeNoCachePresentWithClaims() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - StepVerifier.create(policy.authorizeRequestOnChallenge(this.callContext, // Challenge cache created - this.unauthorizedHttpResponseWithHeaderAndClaims)).assertNext(result -> { - assertFalse(result); - assertNull(this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - }).verifyComplete(); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentWithClaimsSync() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - // Challenge cache created - assertTrue(policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeader)); - - String firstToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(firstToken.isEmpty()); - assertTrue(firstToken.startsWith(BEARER)); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - // Challenge with claims received - assertTrue( - policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeaderAndClaims)); - - String newToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(newToken.isEmpty()); - assertTrue(newToken.startsWith(BEARER)); - - assertNotEquals(firstToken, newToken); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeNoCachePresentWithClaimsSync() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // Challenge with claims received - assertFalse( - policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeaderAndClaims)); - assertNull(this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onAuthorizeRequestNoCache() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // No challenge cache to use - SyncAsyncExtension.execute(() -> policy.authorizeRequestSync(this.callContext), - () -> policy.authorizeRequest(this.callContext)); - - assertNull(this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - } - - @SyncAsyncTest - public void testSetContentLengthHeader() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.bodyContext, this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.bodyFluxContext, this.unauthorizedHttpResponseWithHeader)); - - // Validate that the onChallengeSync ran successfully. - assertTrue(onChallenge); - - HttpHeaders headers = this.bodyFluxContext.getHttpRequest().getHeaders(); - String tokenValue = headers.getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - assertEquals("21", headers.getValue(HttpHeaderName.CONTENT_LENGTH)); - - HttpHeaders syncHeaders = this.bodyContext.getHttpRequest().getHeaders(); - String syncTokenValue = headers.getValue(AUTHORIZATION); - assertFalse(syncTokenValue.isEmpty()); - assertTrue(syncTokenValue.startsWith(BEARER)); - assertEquals("21", syncHeaders.getValue(HttpHeaderName.CONTENT_LENGTH)); - } - - @SyncAsyncTest - public void onAuthorizeRequestNoScope() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.callContext, this.unauthorizedHttpResponseWithoutHeader), - () -> onChallengeAndClearCache(policy, this.callContext, this.unauthorizedHttpResponseWithoutHeader)); - - assertFalse(onChallenge); - } - - @Test - public void onAuthorizeRequestDifferentScope() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - assertThrows(RuntimeException.class, () -> onChallengeAndClearCacheSync(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader)); - - StepVerifier - .create( - onChallengeAndClearCache(policy, this.differentScopeContext, this.unauthorizedHttpResponseWithHeader)) - .verifyErrorMessage("The challenge resource 'https://vault.azure.net/.default' does not match the " - + "requested domain. If you wish to disable this check for your client, pass 'true' to the " - + "SecretClientBuilder.disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information."); - } - - @SyncAsyncTest - public void onAuthorizeRequestDifferentScopeVerifyFalse() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, true); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader)); - - assertTrue(onChallenge); - } - - // Normal flow: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 200 OK - @SyncAsyncTest - public void processMultipleResponses() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - simpleResponse }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request. - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - // On receiving an unauthorized response with claims, the token should be updated and a new attempt to make the - // original request should be made. - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the response with claims and set on the request. - assertNotNull(newToken); - // The token was updated. - assertNotEquals(firstToken, newToken); - // A subsequent request was successful. - assertEquals(simpleResponse, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 401 Unauthorized with claims - @SyncAsyncTest - public void processConsecutiveResponsesWithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - // If a second consecutive unauthorized response with claims is received, it shall be returned as is. - unauthorizedHttpResponseWithHeaderAndClaims, }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the first response with claims and set on the request - assertNotEquals(firstToken, newToken); - // A subsequent request was unsuccessful. - assertEquals(unauthorizedHttpResponseWithHeaderAndClaims, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 401 Unauthorized - @SyncAsyncTest - public void process401WithoutClaimsAfter401WithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - // If a second consecutive unauthorized response is received, it shall be returned as is. - unauthorizedHttpResponseWithHeader }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the first response with claims and set on the request - assertNotEquals(firstToken, newToken); - // A subsequent request was unsuccessful. - assertEquals(unauthorizedHttpResponseWithHeader, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 401 Unauthorized with claims -> 200 OK - @SyncAsyncTest - public void process401WithClaimsAfter401WithoutClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)); - final String[] firstToken = new String[1]; - - testCredential.addAssertion(tokenRequestContext -> { - // This will ensure that that the first request does not contains claims, but the second does after - // receiving a 401 response with a challenge with claims. - testCredential.replaceAssertion( - anotherTokenRequestContext -> DECODED_CLAIMS.equals(anotherTokenRequestContext.getClaims()), 3); - - // We will also store the value of the first credential before it changes on a second call - firstToken[0] = Base64Util.encodeToString(testCredential.getCredential().getBytes(StandardCharsets.UTF_8)); - - assertNotNull(firstToken[0]); - - return tokenRequestContext.getClaims() == null; - }); - - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - unauthorizedHttpResponseWithHeaderAndClaims, - simpleResponse }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first unauthorized response caused a token to be set on the request, then the token was updated on a - // subsequent unauthorized response with claims. - assertNotEquals(firstToken[0], newToken); - // Finally, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - private Mono onChallengeAndClearCache(KeyVaultCredentialPolicy policy, HttpPipelineCallContext callContext, - HttpResponse unauthorizedHttpResponse) { - Mono onChallenge = policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponse); - - KeyVaultCredentialPolicy.clearCache(); - - return onChallenge; - } - - private boolean onChallengeAndClearCacheSync(KeyVaultCredentialPolicy policy, HttpPipelineCallContext callContext, - HttpResponse unauthorizedHttpResponse) { - boolean onChallengeSync = policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponse); - - KeyVaultCredentialPolicy.clearCache(); - - return onChallengeSync; - } - - private static final class MutableTestCredential implements TokenCredential { - private String credential; - private List> assertions; - - private MutableTestCredential(List> assertions) { - this.credential = new Random().toString(); - this.assertions = assertions; - } - - /** - * @throws RuntimeException if any of the assertions fail. - */ - @Override - public Mono getToken(TokenRequestContext requestContext) { - if (requestContext.isCaeEnabled() && requestContext.getClaims() != null) { - credential = new Random().toString(); - } - - String encodedCredential = Base64Util.encodeToString(credential.getBytes(StandardCharsets.UTF_8)); - - for (int i = 0; i < assertions.size(); i++) { - if (!assertions.get(i).apply(requestContext)) { - return Mono.error(new RuntimeException(String.format("Assertion number %d failed", i))); - } - } - - return Mono.fromCallable(() -> new AccessToken(encodedCredential, OffsetDateTime.MAX.minusYears(1))); - } - - private MutableTestCredential setAssertions(List> assertions) { - this.assertions = assertions; - - return this; - } - - private MutableTestCredential addAssertion(Function assertion) { - assertions.add(assertion); - - return this; - } - - private MutableTestCredential replaceAssertion(Function assertion, int index) { - assertions.set(index, assertion); - - return this; - } - - private String getCredential() { - return this.credential; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java deleted file mode 100644 index aa09df2fc221..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys; - -import com.azure.core.util.CoreUtils; -import org.junit.jupiter.api.Test; - -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultKeysUserAgentPropertiesTest { - - @Test - public void testAzureConfiguration() { - Map properties = CoreUtils.getProperties("azure-key-vault-keys.properties"); - - assertTrue(properties.get("name").matches("azure-security-keyvault-keys")); - assertTrue(properties.get("version").matches("(\\d)+.(\\d)+.(\\d)+([-a-zA-Z0-9.])*")); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/TestUtils.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/TestUtils.java deleted file mode 100644 index f411454762fd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/TestUtils.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys; - -import com.azure.core.credential.AccessToken; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import reactor.core.publisher.Mono; - -import java.time.OffsetDateTime; - -/** - * Common test utilities. - */ -public final class TestUtils { - private static final HttpHeaderName CUSTOM_HEADER = HttpHeaderName.fromString("Custom-Header"); - - /** - * Private constructor so this class cannot be instantiated. - */ - private TestUtils() { - } - - public static class PerCallPolicy implements HttpPipelinePolicy { - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.getHttpRequest().setHeader(CUSTOM_HEADER, "Some Value"); - - return next.process(); - } - - @Override - public HttpPipelinePosition getPipelinePosition() { - return HttpPipelinePosition.PER_CALL; - } - } - - public static class PerRetryPolicy implements HttpPipelinePolicy { - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.getHttpRequest().setHeader(CUSTOM_HEADER, "Some Value"); - - return next.process(); - } - } - - public static class TestCredential implements TokenCredential { - @Override - public Mono getToken(TokenRequestContext request) { - return Mono.just(new AccessToken("TestAccessToken", OffsetDateTime.now().plusHours(1))); - } - } - - public static HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertSync().build(); - } - - public static HttpClient buildAsyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertAsync().build(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilderTest.java deleted file mode 100644 index 37b64bd1f4e3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilderTest.java +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import com.azure.security.keyvault.keys.KeyClientBuilder; -import com.azure.security.keyvault.keys.TestUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class CryptographyClientBuilderTest { - private String keyIdentifier; - private CryptographyServiceVersion serviceVersion; - - @BeforeEach - public void setUp() { - keyIdentifier = "https://key-vault-url.vault.azure.net/keys/TestKey/someVersion"; - serviceVersion = CryptographyServiceVersion.V7_3; - } - - @Test - public void buildSyncClientTest() { - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(cryptographyClient); - assertEquals(CryptographyClient.class.getSimpleName(), cryptographyClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(cryptographyClient); - assertEquals(CryptographyClient.class.getSimpleName(), cryptographyClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientWithoutKeyVersionTest() { - String versionlessKeyIdentifier = "https://key-vault-url.vault.azure.net/keys/TestKey"; - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(versionlessKeyIdentifier) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(cryptographyClient); - assertEquals(CryptographyClient.class.getSimpleName(), cryptographyClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientWithPortInKeyIdentifierTest() { - String keyIdentifierWithPort = "https://key-vault-url.vault.azure.net:443/keys/TestKey"; - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifierWithPort) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(cryptographyClient); - assertEquals(CryptographyClient.class.getSimpleName(), cryptographyClient.getClass().getSimpleName()); - assertTrue(cryptographyClient.getVaultUrl().contains(":443")); - } - - @Test - public void buildAsyncClientTest() { - CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(cryptographyAsyncClient); - assertEquals(CryptographyAsyncClient.class.getSimpleName(), cryptographyAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(cryptographyAsyncClient); - assertEquals(CryptographyAsyncClient.class.getSimpleName(), cryptographyAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientWithoutKeyVersionTest() { - String versionlessKeyIdentifier = "https://key-vault-url.vault.azure.net/keys/TestKey"; - CryptographyAsyncClient cryptographyAsyncClient - = new CryptographyClientBuilder().keyIdentifier(versionlessKeyIdentifier) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(cryptographyAsyncClient); - assertEquals(CryptographyAsyncClient.class.getSimpleName(), cryptographyAsyncClient.getClass().getSimpleName()); - } - - @Test - public void emptyVaultUrlThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new KeyClientBuilder().vaultUrl("")); - } - - @Test - public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new KeyClientBuilder().credential(null)); - } - - @Test - public void clientOptionsIsPreferredOverLogOptions() { - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, cryptographyClient::getKey); - } - - @Test - public void applicationIdFallsBackToLogOptions() { - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, cryptographyClient::getKey); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - CryptographyClient cryptographyClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .credential(new TestUtils.TestCredential()) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, cryptographyClient::getKey); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient()); - } - - // This tests the policy is in the right place because if it were added per retry, it would be after the credentials - // and auth would fail because we changed a signed header. - @Test - public void addPerCallPolicy() { - CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder().keyIdentifier(keyIdentifier) - .credential(new TestUtils.TestCredential()) - .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - HttpPipeline pipeline = cryptographyAsyncClient.getHttpPipeline(); - int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; - - for (int i = 0; i < pipeline.getPolicyCount(); i++) { - if (pipeline.getPolicy(i).getClass() == RetryPolicy.class) { - retryPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerCallPolicy.class) { - perCallPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerRetryPolicy.class) { - perRetryPolicyPosition = i; - } - } - - assertTrue(perCallPolicyPosition != -1); - assertTrue(perCallPolicyPosition < retryPolicyPosition); - assertTrue(retryPolicyPosition < perRetryPolicyPosition); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientManagedHsmTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientManagedHsmTest.java deleted file mode 100644 index 6bbb04f57d55..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientManagedHsmTest.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.test.TestMode; -import com.azure.core.util.Configuration; -import org.junit.jupiter.api.condition.EnabledIf; - -import static com.azure.security.keyvault.keys.KeyClientTestBase.TEST_MODE; - -@EnabledIf("shouldRunHsmTest") -public class CryptographyClientManagedHsmTest extends CryptographyClientTest { - public CryptographyClientManagedHsmTest() { - this.isHsmEnabled = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; - this.runManagedHsmTest = shouldRunHsmTest(); - } - - public static boolean shouldRunHsmTest() { - return Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null - || TEST_MODE == TestMode.PLAYBACK; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java deleted file mode 100644 index fdd43739ea5b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java +++ /dev/null @@ -1,433 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.http.HttpClient; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignResult; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyOperation; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.Security; -import java.security.spec.ECGenParameterSpec; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import static com.azure.security.keyvault.keys.TestUtils.buildSyncAssertingClient; -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -public class CryptographyClientTest extends CryptographyClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(CryptographyClientTest.class); - - private KeyClient client; - - @Override - protected void beforeTest() { - beforeTestSetup(); - } - - private void initializeKeyClient(HttpClient httpClient) { - client = getKeyClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - getEndpoint(), null).buildClient(); - } - - CryptographyClient initializeCryptographyClient(String keyId, HttpClient httpClient, - CryptographyServiceVersion serviceVersion) { - return getCryptographyClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - serviceVersion).keyIdentifier(keyId).buildClient(); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void encryptDecryptRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) throws Exception { - initializeKeyClient(httpClient); - - encryptDecryptRsaRunner(keyPair -> { - JsonWebKey key = JsonWebKey.fromRsa(keyPair); - String keyName = testResourceNamer.randomName("testRsaKey", 20); - KeyVaultKey importedKey = client.importKey(keyName, key); - CryptographyClient cryptoClient - = initializeCryptographyClient(importedKey.getId(), httpClient, serviceVersion); - - List algorithms = Arrays.asList(EncryptionAlgorithm.RSA1_5, - EncryptionAlgorithm.RSA_OAEP, EncryptionAlgorithm.RSA_OAEP_256); - - for (EncryptionAlgorithm algorithm : algorithms) { - // Test variables - byte[] plaintext = new byte[100]; - - new Random(0x1234567L).nextBytes(plaintext); - - byte[] ciphertext = cryptoClient.encrypt(algorithm, plaintext).getCipherText(); - byte[] decryptedText = cryptoClient.decrypt(algorithm, ciphertext).getPlainText(); - - assertArrayEquals(decryptedText, plaintext); - - ciphertext = cryptoClient.encrypt(algorithm, plaintext).getCipherText(); - decryptedText = cryptoClient.decrypt(algorithm, ciphertext).getPlainText(); - - assertArrayEquals(decryptedText, plaintext); - } - }); - } - - @Test - public void encryptDecryptRsaLocal() throws Exception { - encryptDecryptRsaRunner(keyPair -> { - JsonWebKey key = JsonWebKey.fromRsa(keyPair, Arrays.asList(KeyOperation.ENCRYPT, KeyOperation.DECRYPT)); - CryptographyClient cryptoClient = initializeCryptographyClient(key); - List algorithms - = Arrays.asList(EncryptionAlgorithm.RSA1_5, EncryptionAlgorithm.RSA_OAEP); - - for (EncryptionAlgorithm algorithm : algorithms) { - // Test variables - byte[] plainText = new byte[100]; - - new Random(0x1234567L).nextBytes(plainText); - - byte[] cipherText = cryptoClient.encrypt(algorithm, plainText).getCipherText(); - byte[] decryptedText = cryptoClient.decrypt(algorithm, cipherText).getPlainText(); - - assertArrayEquals(decryptedText, plainText); - } - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void wrapUnwrapRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) throws Exception { - initializeKeyClient(httpClient); - - encryptDecryptRsaRunner(keyPair -> { - JsonWebKey key = JsonWebKey.fromRsa(keyPair); - String keyName = testResourceNamer.randomName("testRsaKeyWrapUnwrap", 25); - KeyVaultKey importedKey = client.importKey(keyName, key); - CryptographyClient cryptoClient - = initializeCryptographyClient(importedKey.getId(), httpClient, serviceVersion); - List algorithms - = Arrays.asList(KeyWrapAlgorithm.RSA1_5, KeyWrapAlgorithm.RSA_OAEP, KeyWrapAlgorithm.RSA_OAEP_256); - - for (KeyWrapAlgorithm algorithm : algorithms) { - // Test variables - byte[] plaintext = new byte[100]; - - new Random(0x1234567L).nextBytes(plaintext); - - byte[] encryptedKey = cryptoClient.wrapKey(algorithm, plaintext).getEncryptedKey(); - byte[] decryptedKey = cryptoClient.unwrapKey(algorithm, encryptedKey).getKey(); - - assertArrayEquals(decryptedKey, plaintext); - - encryptedKey = cryptoClient.wrapKey(algorithm, plaintext).getEncryptedKey(); - decryptedKey = cryptoClient.unwrapKey(algorithm, encryptedKey).getKey(); - - assertArrayEquals(decryptedKey, plaintext); - } - - }); - } - - @Test - public void wrapUnwrapRsaLocal() throws Exception { - encryptDecryptRsaRunner(keyPair -> { - JsonWebKey key = JsonWebKey.fromRsa(keyPair, Arrays.asList(KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY)); - CryptographyClient cryptoClient = initializeCryptographyClient(key); - List algorithms = Arrays.asList(KeyWrapAlgorithm.RSA1_5, KeyWrapAlgorithm.RSA_OAEP); - - for (KeyWrapAlgorithm algorithm : algorithms) { - // Test variables - byte[] plainText = new byte[100]; - - new Random(0x1234567L).nextBytes(plainText); - - byte[] encryptedKey = cryptoClient.wrapKey(algorithm, plainText).getEncryptedKey(); - byte[] decryptedKey = cryptoClient.unwrapKey(algorithm, encryptedKey).getKey(); - - assertArrayEquals(decryptedKey, plainText); - } - - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void signVerifyEc(HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - initializeKeyClient(httpClient); - - signVerifyEcRunner(signVerifyEcData -> { - KeyCurveName curve = signVerifyEcData.getCurve(); - Map curveToSignature = signVerifyEcData.getCurveToSignature(); - Map messageDigestAlgorithm = signVerifyEcData.getMessageDigestAlgorithm(); - String keyName = testResourceNamer.randomName("testEcKey" + curve.toString(), 20); - CreateEcKeyOptions createEcKeyOptions - = new CreateEcKeyOptions(keyName).setKeyOperations(KeyOperation.SIGN, KeyOperation.VERIFY) - .setCurveName(curve); - KeyVaultKey keyVaultKey = client.createEcKey(createEcKeyOptions); - CryptographyClient cryptographyClient - = initializeCryptographyClient(keyVaultKey.getId(), httpClient, serviceVersion); - - try { - byte[] data = new byte[100]; - - new Random(0x1234567L).nextBytes(data); - - MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm.get(curve)); - - md.update(data); - - byte[] digest = md.digest(); - - SignResult signResult = cryptographyClient.sign(curveToSignature.get(curve), digest); - - Boolean verifyStatus - = cryptographyClient.verify(curveToSignature.get(curve), digest, signResult.getSignature()) - .isValid(); - - assertTrue(verifyStatus); - } catch (NoSuchAlgorithmException e) { - fail(e); - } - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void signDataVerifyEc(HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - initializeKeyClient(httpClient); - - signVerifyEcRunner(signVerifyEcData -> { - KeyCurveName curve = signVerifyEcData.getCurve(); - Map curveToSignature = signVerifyEcData.getCurveToSignature(); - String keyName = testResourceNamer.randomName("testEcKey" + curve.toString(), 20); - CreateEcKeyOptions createEcKeyOptions - = new CreateEcKeyOptions(keyName).setKeyOperations(KeyOperation.SIGN, KeyOperation.VERIFY) - .setCurveName(curve); - KeyVaultKey keyVaultKey = client.createEcKey(createEcKeyOptions); - CryptographyClient cryptographyClient - = initializeCryptographyClient(keyVaultKey.getId(), httpClient, serviceVersion); - - byte[] plaintext = new byte[100]; - - new Random(0x1234567L).nextBytes(plaintext); - - byte[] signature = cryptographyClient.signData(curveToSignature.get(curve), plaintext).getSignature(); - - Boolean verifyStatus - = cryptographyClient.verifyData(curveToSignature.get(curve), plaintext, signature).isValid(); - - assertTrue(verifyStatus); - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void signVerifyRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) throws Exception { - initializeKeyClient(httpClient); - - encryptDecryptRsaRunner(keyPair -> { - JsonWebKey key = JsonWebKey.fromRsa(keyPair); - String keyName = testResourceNamer.randomName("testRsaKeySignVerify", 25); - KeyVaultKey importedKey = client.importKey(keyName, key); - CryptographyClient cryptoClient - = initializeCryptographyClient(importedKey.getId(), httpClient, serviceVersion); - List algorithms - = Arrays.asList(SignatureAlgorithm.RS256, SignatureAlgorithm.RS384, SignatureAlgorithm.RS512); - - Map messageDigestAlgorithm = new HashMap<>(); - - messageDigestAlgorithm.put(SignatureAlgorithm.RS256, "SHA-256"); - messageDigestAlgorithm.put(SignatureAlgorithm.RS384, "SHA-384"); - messageDigestAlgorithm.put(SignatureAlgorithm.RS512, "SHA-512"); - - for (SignatureAlgorithm algorithm : algorithms) { - try { - byte[] data = new byte[100]; - - new Random(0x1234567L).nextBytes(data); - - MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm.get(algorithm)); - - md.update(data); - - byte[] digest = md.digest(); - - SignResult signResult = cryptoClient.sign(algorithm, digest); - Boolean verifyStatus = cryptoClient.verify(algorithm, digest, signResult.getSignature()).isValid(); - - assertTrue(verifyStatus); - } catch (NoSuchAlgorithmException e) { - fail(e); - } - } - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void signDataVerifyRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) throws Exception { - initializeKeyClient(httpClient); - - encryptDecryptRsaRunner(keyPair -> { - JsonWebKey key = JsonWebKey.fromRsa(keyPair); - String keyName = testResourceNamer.randomName("testRsaKeySignVerify", 25); - KeyVaultKey importedKey = client.importKey(keyName, key); - CryptographyClient cryptoClient - = initializeCryptographyClient(importedKey.getId(), httpClient, serviceVersion); - List algorithms - = Arrays.asList(SignatureAlgorithm.RS256, SignatureAlgorithm.RS384, SignatureAlgorithm.RS512); - - for (SignatureAlgorithm algorithm : algorithms) { - byte[] plaintext = new byte[100]; - - new Random(0x1234567L).nextBytes(plaintext); - - byte[] signature = cryptoClient.signData(algorithm, plaintext).getSignature(); - Boolean verifyStatus = cryptoClient.verifyData(algorithm, plaintext, signature).isValid(); - - assertTrue(verifyStatus); - } - }); - } - - @Test - public void signDataVerifyEcLocal() { - signVerifyEcRunner(signVerifyEcData -> { - KeyPair keyPair; - Provider provider = null; - - try { - String algorithmName = "EC"; - Provider[] providers = Security.getProviders(); - - for (Provider currentProvider : providers) { - if (currentProvider.containsValue(algorithmName)) { - provider = currentProvider; - - break; - } - } - - if (provider == null) { - for (Provider currentProvider : providers) { - System.out.println(currentProvider.getName()); - } - - fail(String.format("No suitable security provider for algorithm %s was found.", algorithmName)); - } - - final KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithmName, provider); - ECGenParameterSpec spec - = new ECGenParameterSpec(signVerifyEcData.getCurveToSpec().get(signVerifyEcData.getCurve())); - - generator.initialize(spec); - - keyPair = generator.generateKeyPair(); - } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException e) { - // Could not generate a KeyPair from the given JsonWebKey. - // It's likely this happened for key curve secp256k1, which is not supported on Java 16+. - LOGGER.log(LogLevel.VERBOSE, () -> "Failed to generate key pair from JsonWebKey.", e); - - return; - } - - JsonWebKey jsonWebKey - = JsonWebKey.fromEc(keyPair, provider, Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY)); - KeyCurveName curve = signVerifyEcData.getCurve(); - Map curveToSignature = signVerifyEcData.getCurveToSignature(); - CryptographyClient cryptographyClient = initializeCryptographyClient(jsonWebKey); - - byte[] plainText = new byte[100]; - - new Random(0x1234567L).nextBytes(plainText); - - byte[] signature = cryptographyClient.signData(curveToSignature.get(curve), plainText).getSignature(); - Boolean verifyStatus - = cryptographyClient.verifyData(curveToSignature.get(curve), plainText, signature).isValid(); - - assertTrue(verifyStatus); - }); - } - - @Test - public void encryptDecryptAes128CbcLocal() throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(plaintext, iv); - - encryptDecryptAesCbc(128, encryptParameters); - } - - @Test - public void encryptDecryptAes192CbcLocal() throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - EncryptParameters encryptParameters = EncryptParameters.createA192CbcParameters(plaintext, iv); - - encryptDecryptAesCbc(256, encryptParameters); - } - - @Test - public void encryptDecryptAes256CbcLocal() throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - EncryptParameters encryptParameters = EncryptParameters.createA256CbcParameters(plaintext, iv); - - encryptDecryptAesCbc(256, encryptParameters); - } - - @Test - public void encryptDecryptAes128CbcPadLocal() throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - EncryptParameters encryptParameters = EncryptParameters.createA128CbcPadParameters(plaintext, iv); - - encryptDecryptAesCbc(128, encryptParameters); - } - - @Test - public void encryptDecryptAes192CbcPadLocal() throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - EncryptParameters encryptParameters = EncryptParameters.createA192CbcPadParameters(plaintext, iv); - - encryptDecryptAesCbc(192, encryptParameters); - } - - @Test - public void encryptDecryptAes256CbcPadLocal() throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - EncryptParameters encryptParameters = EncryptParameters.createA256CbcPadParameters(plaintext, iv); - - encryptDecryptAesCbc(256, encryptParameters); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java deleted file mode 100644 index 5ba32c65b832..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.BodilessMatcher; -import com.azure.core.test.models.CustomMatcher; -import com.azure.core.test.models.TestProxyRequestMatcher; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.identity.AzurePowerShellCredentialBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClientBuilder; -import com.azure.security.keyvault.keys.KeyServiceVersion; -import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; -import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; -import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; -import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyOperation; -import org.junit.jupiter.api.Test; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.NoSuchAlgorithmException; -import java.security.spec.KeySpec; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Consumer; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -public abstract class CryptographyClientTestBase extends TestProxyTestBase { - private static final ClientLogger LOGGER = new ClientLogger(CryptographyClientTestBase.class); - - protected boolean isHsmEnabled = false; - protected boolean runManagedHsmTest = false; - - private static final int MAX_RETRIES = 5; - private static final RetryOptions LIVE_RETRY_OPTIONS - = new RetryOptions(new ExponentialBackoffOptions().setMaxRetries(MAX_RETRIES) - .setBaseDelay(Duration.ofSeconds(2)) - .setMaxDelay(Duration.ofSeconds(16))); - - private static final RetryOptions PLAYBACK_RETRY_OPTIONS - = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); - - void beforeTestSetup() { - KeyVaultCredentialPolicy.clearCache(); - } - - KeyClientBuilder getKeyClientBuilder(HttpClient httpClient, String endpoint, KeyServiceVersion serviceVersion) { - TokenCredential credential; - - if (interceptorManager.isLiveMode()) { - credential = new AzurePowerShellCredentialBuilder().additionallyAllowedTenants("*").build(); - } else if (interceptorManager.isRecordMode()) { - credential = new DefaultAzureCredentialBuilder().additionallyAllowedTenants("*").build(); - } else { - credential = new MockTokenCredential(); - - List customMatchers = new ArrayList<>(); - customMatchers.add(new BodilessMatcher()); - customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); - interceptorManager.addMatchers(customMatchers); - } - - KeyClientBuilder builder = new KeyClientBuilder().vaultUrl(endpoint) - .serviceVersion(serviceVersion) - .credential(credential) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - return interceptorManager.isRecordMode() - ? builder.addPolicy(interceptorManager.getRecordPolicy()) - : builder; - } - } - - CryptographyClientBuilder getCryptographyClientBuilder(HttpClient httpClient, - CryptographyServiceVersion serviceVersion) { - TokenCredential credential; - - if (interceptorManager.isLiveMode()) { - credential = new AzurePowerShellCredentialBuilder().additionallyAllowedTenants("*").build(); - } else if (interceptorManager.isRecordMode()) { - credential = new DefaultAzureCredentialBuilder().additionallyAllowedTenants("*").build(); - } else { - credential = new MockTokenCredential(); - - List customMatchers = new ArrayList<>(); - customMatchers.add(new BodilessMatcher()); - customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); - interceptorManager.addMatchers(customMatchers); - } - - CryptographyClientBuilder builder = new CryptographyClientBuilder().serviceVersion(serviceVersion) - .credential(credential) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - return interceptorManager.isRecordMode() - ? builder.addPolicy(interceptorManager.getRecordPolicy()) - : builder; - } - } - - static CryptographyClient initializeCryptographyClient(JsonWebKey key) { - return new CryptographyClientBuilder().jsonWebKey(key).buildClient(); - } - - @Test - public abstract void encryptDecryptRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) - throws Exception; - - @Test - public abstract void encryptDecryptRsaLocal() throws Exception; - - void encryptDecryptRsaRunner(Consumer testRunner) throws Exception { - testRunner.accept(getWellKnownKey()); - } - - @Test - public abstract void encryptDecryptAes128CbcLocal() throws Exception; - - @Test - public abstract void encryptDecryptAes192CbcLocal() throws Exception; - - @Test - public abstract void encryptDecryptAes256CbcLocal() throws Exception; - - @Test - public abstract void encryptDecryptAes128CbcPadLocal() throws Exception; - - @Test - public abstract void encryptDecryptAes192CbcPadLocal() throws Exception; - - @Test - public abstract void encryptDecryptAes256CbcPadLocal() throws Exception; - - @Test - public abstract void signVerifyEc(HttpClient httpClient, CryptographyServiceVersion serviceVersion) - throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; - - @Test - public abstract void signDataVerifyEc(HttpClient httpClient, CryptographyServiceVersion serviceVersion) - throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; - - void signVerifyEcRunner(Consumer testRunner) { - Map curveToSignature = new HashMap<>(); - - curveToSignature.put(KeyCurveName.P_256, SignatureAlgorithm.ES256); - curveToSignature.put(KeyCurveName.P_384, SignatureAlgorithm.ES384); - curveToSignature.put(KeyCurveName.P_521, SignatureAlgorithm.ES512); - curveToSignature.put(KeyCurveName.P_256K, SignatureAlgorithm.ES256K); - - Map curveToSpec = new HashMap<>(); - - curveToSpec.put(KeyCurveName.P_256, "secp256r1"); - curveToSpec.put(KeyCurveName.P_384, "secp384r1"); - curveToSpec.put(KeyCurveName.P_521, "secp521r1"); - curveToSpec.put(KeyCurveName.P_256K, "secp256k1"); - - Map messageDigestAlgorithm = new HashMap<>(); - - messageDigestAlgorithm.put(KeyCurveName.P_256, "SHA-256"); - messageDigestAlgorithm.put(KeyCurveName.P_384, "SHA-384"); - messageDigestAlgorithm.put(KeyCurveName.P_521, "SHA-512"); - messageDigestAlgorithm.put(KeyCurveName.P_256K, "SHA-256"); - - List curveList = new ArrayList<>(); - - curveList.add(KeyCurveName.P_256); - curveList.add(KeyCurveName.P_384); - curveList.add(KeyCurveName.P_521); - curveList.add(KeyCurveName.P_256K); - - for (KeyCurveName curve : curveList) { - testRunner.accept(new SignVerifyEcData(curve, curveToSignature, curveToSpec, messageDigestAlgorithm)); - } - } - - protected static class SignVerifyEcData { - private final KeyCurveName curve; - private final Map curveToSignature; - private final Map curveToSpec; - private final Map messageDigestAlgorithm; - - public SignVerifyEcData(KeyCurveName curve, Map curveToSignature, - Map curveToSpec, Map messageDigestAlgorithm) { - this.curve = curve; - this.curveToSignature = curveToSignature; - this.curveToSpec = curveToSpec; - this.messageDigestAlgorithm = messageDigestAlgorithm; - } - - public KeyCurveName getCurve() { - return curve; - } - - public Map getCurveToSignature() { - return curveToSignature; - } - - public Map getCurveToSpec() { - return curveToSpec; - } - - public Map getMessageDigestAlgorithm() { - return messageDigestAlgorithm; - } - } - - @Test - public abstract void signDataVerifyEcLocal() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; - - @Test - public abstract void wrapUnwrapRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) - throws Exception; - - @Test - public abstract void wrapUnwrapRsaLocal() throws Exception; - - @Test - public abstract void signVerifyRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) - throws Exception; - - @Test - public abstract void signDataVerifyRsa(HttpClient httpClient, CryptographyServiceVersion serviceVersion) - throws Exception; - - private static KeyPair getWellKnownKey() throws Exception { - BigInteger modulus = new BigInteger( - "27266783713040163753473734334021230592631652450892850648620119914958066181400432364213298181846462385257448168605902438305568194683691563208578540343969522651422088760509452879461613852042845039552547834002168737350264189810815735922734447830725099163869215360401162450008673869707774119785881115044406101346450911054819448375712432746968301739007624952483347278954755460152795801894283389540036131881712321193750961817346255102052653789197325341350920441746054233522546543768770643593655942246891652634114922277138937273034902434321431672058220631825053788262810480543541597284376261438324665363067125951152574540779"); - BigInteger publicExponent = new BigInteger("65537"); - BigInteger privateExponent = new BigInteger( - "10466613941269075477152428927796086150095892102279802916937552172064636326433780566497000814207416485739683286961848843255766652023400959086290344987308562817062506476465756840999981989957456897020361717197805192876094362315496459535960304928171129585813477132331538577519084006595335055487028872410579127692209642938724850603554885478763205394868103298473476811627231543504190652483290944218004086457805431824328448422034887148115990501701345535825110962804471270499590234116100216841170344686381902328362376624405803648588830575558058257742073963036264273582756620469659464278207233345784355220317478103481872995809"); - BigInteger primeP = new BigInteger( - "175002941104568842715096339107566771592009112128184231961529953978142750732317724951747797764638217287618769007295505214923187971350518217670604044004381362495186864051394404165602744235299100790551775147322153206730562450301874236875459336154569893255570576967036237661594595803204808064127845257496057219227"); - BigInteger primeQ = new BigInteger( - "155807574095269324897144428622185380283967159190626345335083690114147315509962698765044950001909553861571493035240542031420213144237033208612132704562174772894369053916729901982420535940939821673277140180113593951522522222348910536202664252481405241042414183668723338300649954708432681241621374644926879028977"); - BigInteger primeExponentP = new BigInteger( - "79745606804504995938838168837578376593737280079895233277372027184693457251170125851946171360348440134236338520742068873132216695552312068793428432338173016914968041076503997528137698610601222912385953171485249299873377130717231063522112968474603281996190849604705284061306758152904594168593526874435238915345"); - BigInteger primeExponentQ = new BigInteger( - "80619964983821018303966686284189517841976445905569830731617605558094658227540855971763115484608005874540349730961777634427740786642996065386667564038755340092176159839025706183161615488856833433976243963682074011475658804676349317075370362785860401437192843468423594688700132964854367053490737073471709030801"); - BigInteger crtCoefficient = new BigInteger( - "2157818511040667226980891229484210846757728661751992467240662009652654684725325675037512595031058612950802328971801913498711880111052682274056041470625863586779333188842602381844572406517251106159327934511268610438516820278066686225397795046020275055545005189953702783748235257613991379770525910232674719428"); - KeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent); - KeySpec privateKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, - primeExponentP, primeExponentQ, crtCoefficient); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - - return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); - } - - static void encryptDecryptAesCbc(int keySize, EncryptParameters encryptParameters) throws NoSuchAlgorithmException { - byte[] plaintext = "My16BitPlaintext".getBytes(); - byte[] iv = "My16BytesTestIv.".getBytes(); - CryptographyClient cryptographyClient = initializeCryptographyClient(getTestJsonWebKey(keySize)); - EncryptResult encryptResult = cryptographyClient.encrypt(encryptParameters, Context.NONE); - EncryptionAlgorithm algorithm = encryptParameters.getAlgorithm(); - DecryptParameters decryptParameters = null; - - if (algorithm == EncryptionAlgorithm.A128CBC) { - decryptParameters = DecryptParameters.createA128CbcParameters(encryptResult.getCipherText(), iv); - } else if (algorithm == EncryptionAlgorithm.A192CBC) { - decryptParameters = DecryptParameters.createA192CbcParameters(encryptResult.getCipherText(), iv); - } else if (algorithm == EncryptionAlgorithm.A256CBC) { - decryptParameters = DecryptParameters.createA256CbcParameters(encryptResult.getCipherText(), iv); - } else if (algorithm == EncryptionAlgorithm.A128CBCPAD) { - decryptParameters = DecryptParameters.createA128CbcPadParameters(encryptResult.getCipherText(), iv); - } else if (algorithm == EncryptionAlgorithm.A192CBCPAD) { - decryptParameters = DecryptParameters.createA192CbcPadParameters(encryptResult.getCipherText(), iv); - } else if (algorithm == EncryptionAlgorithm.A256CBCPAD) { - decryptParameters = DecryptParameters.createA256CbcPadParameters(encryptResult.getCipherText(), iv); - } - - DecryptResult decryptResult = cryptographyClient.decrypt(decryptParameters, Context.NONE); - - assertArrayEquals(plaintext, decryptResult.getPlainText()); - } - - private static JsonWebKey getTestJsonWebKey(int keySize) throws NoSuchAlgorithmException { - KeyGenerator keyGen = KeyGenerator.getInstance("AES"); - - keyGen.init(keySize); - - SecretKey secretKey = keyGen.generateKey(); - - List keyOperations = new ArrayList<>(); - keyOperations.add(KeyOperation.ENCRYPT); - keyOperations.add(KeyOperation.DECRYPT); - - return JsonWebKey.fromAes(secretKey, keyOperations).setId("testKey"); - } - - public String getEndpoint() { - final String endpoint = runManagedHsmTest - ? Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT", "https://localhost:8080") - : Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https://localhost:8080"); - - Objects.requireNonNull(endpoint); - - return endpoint; - } - - public void sleep(long millis) { - sleepIfRunningAgainstService(millis); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilderTest.java deleted file mode 100644 index 53b9b7923ef5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientBuilderTest.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.cryptography.KeyEncryptionKey; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.security.keyvault.keys.TestUtils; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class KeyEncryptionKeyClientBuilderTest { - private static final String KEY_ID - = "https://azure-kv-tests2.vault.azure.net/secrets/secretkey83767501/4d85413d34944863bc9747af78f8f446"; - - @Test - public void buildKeyEncryptionKey() { - KeyEncryptionKey keyEncryptionKey - = new KeyEncryptionKeyClientBuilder().credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildKeyEncryptionKey(KEY_ID); - - assertNotNull(keyEncryptionKey); - assertEquals(KeyEncryptionKeyClient.class.getSimpleName(), keyEncryptionKey.getClass().getSimpleName()); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new KeyEncryptionKeyClientBuilder().credential(new TestUtils.TestCredential()) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildKeyEncryptionKey(KEY_ID)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientManagedHsmTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientManagedHsmTest.java deleted file mode 100644 index 0c15a31d6853..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientManagedHsmTest.java +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.http.HttpClient; -import com.azure.core.test.TestMode; -import com.azure.core.util.Configuration; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyServiceVersion; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyOperation; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.api.condition.EnabledIf; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import java.util.Arrays; - -import static com.azure.security.keyvault.keys.KeyClientTestBase.TEST_MODE; -import static com.azure.security.keyvault.keys.TestUtils.buildSyncAssertingClient; -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -@EnabledIf("shouldRunHsmTest") -public class KeyEncryptionKeyClientManagedHsmTest extends KeyEncryptionKeyClientTest { - private KeyVaultKey keyVaultKey; - - public KeyEncryptionKeyClientManagedHsmTest() { - this.isHsmEnabled = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; - this.runManagedHsmTest = shouldRunHsmTest(); - } - - public static boolean shouldRunHsmTest() { - return Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null - || TEST_MODE == TestMode.PLAYBACK; - } - - private void setupKeyAndClient(JsonWebKey jsonWebKey, HttpClient httpClient, - CryptographyServiceVersion serviceVersion) { - httpClient = buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); - - if (keyVaultKey == null) { - KeyClient keyClient - = getKeyClientBuilder(httpClient, getEndpoint(), KeyServiceVersion.valueOf(serviceVersion.name())) - .buildClient(); - keyVaultKey = keyClient.importKey(testResourceNamer.randomName("symmetricKey", 20), jsonWebKey); - keyEncryptionKey = getKeyEncryptionKeyClientBuilder(httpClient, serviceVersion) - .buildKeyEncryptionKey(keyVaultKey.getId()); - } - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - @Override - public void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - byte[] kek = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - SecretKey secretKeySpec = new SecretKeySpec(kek, "AES"); - JsonWebKey jsonWebKey - = JsonWebKey.fromAes(secretKeySpec, Arrays.asList(KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY)); - - setupKeyAndClient(jsonWebKey, httpClient, serviceVersion); - - byte[] cek = { - 0x00, - 0x11, - 0x22, - 0x33, - 0x44, - 0x55, - 0x66, - 0x77, - (byte) 0x88, - (byte) 0x99, - (byte) 0xAA, - (byte) 0xBB, - (byte) 0xCC, - (byte) 0xDD, - (byte) 0xEE, - (byte) 0xFF }; - byte[] encrypted = keyEncryptionKey.wrapKey("A128KW", cek); - byte[] ek = { - 0x1F, - (byte) 0xA6, - (byte) 0x8B, - 0x0A, - (byte) 0x81, - 0x12, - (byte) 0xB4, - 0x47, - (byte) 0xAE, - (byte) 0xF3, - 0x4B, - (byte) 0xD8, - (byte) 0xFB, - 0x5A, - 0x7B, - (byte) 0x82, - (byte) 0x9D, - 0x3E, - (byte) 0x86, - 0x23, - 0x71, - (byte) 0xD2, - (byte) 0xCF, - (byte) 0xE5 }; - - assertArrayEquals(ek, encrypted); - - byte[] dek = keyEncryptionKey.unwrapKey("A128KW", ek); - - assertArrayEquals(dek, cek); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - @Override - public void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - byte[] kek = { - 0x00, - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0A, - 0x0B, - 0x0C, - 0x0D, - 0x0E, - 0x0F, - 0x10, - 0x11, - 0x12, - 0x13, - 0x14, - 0x15, - 0x16, - 0x17 }; - SecretKey secretKeySpec = new SecretKeySpec(kek, "AES"); - JsonWebKey jsonWebKey - = JsonWebKey.fromAes(secretKeySpec, Arrays.asList(KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY)); - - setupKeyAndClient(jsonWebKey, httpClient, serviceVersion); - - byte[] cek = { - 0x00, - 0x11, - 0x22, - 0x33, - 0x44, - 0x55, - 0x66, - 0x77, - (byte) 0x88, - (byte) 0x99, - (byte) 0xAA, - (byte) 0xBB, - (byte) 0xCC, - (byte) 0xDD, - (byte) 0xEE, - (byte) 0xFF }; - byte[] encrypted = keyEncryptionKey.wrapKey("A192KW", cek); - byte[] ek = { - (byte) 0x96, - 0x77, - (byte) 0x8B, - 0x25, - (byte) 0xAE, - 0x6C, - (byte) 0xA4, - 0x35, - (byte) 0xF9, - 0x2B, - 0x5B, - (byte) 0x97, - (byte) 0xC0, - 0x50, - (byte) 0xAE, - (byte) 0xD2, - 0x46, - (byte) 0x8A, - (byte) 0xB8, - (byte) 0xA1, - 0x7A, - (byte) 0xD8, - 0x4E, - 0x5D }; - - assertArrayEquals(ek, encrypted); - - byte[] dek = keyEncryptionKey.unwrapKey("A192KW", ek); - - assertArrayEquals(dek, cek); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTest.java deleted file mode 100644 index e4bab3ba8dd5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTest.java +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.cryptography.KeyEncryptionKey; -import com.azure.core.http.HttpClient; -import com.azure.core.util.Context; -import com.azure.security.keyvault.keys.cryptography.implementation.CryptographyClientImpl; -import com.azure.security.keyvault.keys.implementation.models.SecretKey; -import com.azure.security.keyvault.keys.models.JsonWebKey; -import com.azure.security.keyvault.keys.models.KeyOperation; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import javax.crypto.spec.SecretKeySpec; -import java.util.Arrays; -import java.util.Base64; - -import static com.azure.security.keyvault.keys.TestUtils.buildSyncAssertingClient; -import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -public class KeyEncryptionKeyClientTest extends KeyEncryptionKeyClientTestBase { - protected KeyEncryptionKey keyEncryptionKey; - - @Override - protected void beforeTest() { - beforeTestSetup(); - } - - private void setupSecretKeyAndClient(byte[] kek, HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - String secretName = testResourceNamer.randomName("secretKey", 20); - HttpClient actualHttpClient = buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); - - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - - String keyId = getEndpoint(); - keyId = keyId.endsWith("/") ? keyId + "secrets/" + secretName : keyId + "/secrets/" + secretName; - CryptographyClientImpl implClient = getCryptographyClientImpl(actualHttpClient, keyId, serviceVersion); - SecretKey secretKey - = implClient.setSecretKey(new SecretKey(secretName, Base64.getEncoder().encodeToString(kek)), Context.NONE) - .getValue(); - - keyEncryptionKey = getKeyEncryptionKeyClientBuilder(actualHttpClient, serviceVersion) - .buildKeyEncryptionKey(secretKey.getId()); - } - - private KeyEncryptionKey setupKeyEncryptionKey(JsonWebKey jsonWebKey) { - return (jsonWebKey != null) ? new KeyEncryptionKeyClientBuilder().buildKeyEncryptionKey(jsonWebKey) : null; - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - byte[] kek = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - - setupSecretKeyAndClient(kek, httpClient, serviceVersion); - - byte[] cek = { - 0x00, - 0x11, - 0x22, - 0x33, - 0x44, - 0x55, - 0x66, - 0x77, - (byte) 0x88, - (byte) 0x99, - (byte) 0xAA, - (byte) 0xBB, - (byte) 0xCC, - (byte) 0xDD, - (byte) 0xEE, - (byte) 0xFF }; - byte[] encrypted = keyEncryptionKey.wrapKey("A128KW", cek); - byte[] ek = { - 0x1F, - (byte) 0xA6, - (byte) 0x8B, - 0x0A, - (byte) 0x81, - 0x12, - (byte) 0xB4, - 0x47, - (byte) 0xAE, - (byte) 0xF3, - 0x4B, - (byte) 0xD8, - (byte) 0xFB, - 0x5A, - 0x7B, - (byte) 0x82, - (byte) 0x9D, - 0x3E, - (byte) 0x86, - 0x23, - 0x71, - (byte) 0xD2, - (byte) 0xCF, - (byte) 0xE5 }; - - assertArrayEquals(ek, encrypted); - - byte[] dek = keyEncryptionKey.unwrapKey("A128KW", ek); - - assertArrayEquals(dek, cek); - } - - @Test - public void wrapUnwrapSymmetricAK128Local() { - byte[] kek = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - JsonWebKey localKey = JsonWebKey - .fromAes(new SecretKeySpec(kek, "AES"), Arrays.asList(KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY)) - .setId("testKey"); - KeyEncryptionKey keyEncryptionKey = setupKeyEncryptionKey(localKey); - byte[] cek = { - 0x00, - 0x11, - 0x22, - 0x33, - 0x44, - 0x55, - 0x66, - 0x77, - (byte) 0x88, - (byte) 0x99, - (byte) 0xAA, - (byte) 0xBB, - (byte) 0xCC, - (byte) 0xDD, - (byte) 0xEE, - (byte) 0xFF }; - byte[] encrypted = keyEncryptionKey.wrapKey("A128KW", cek); - byte[] ek = { - 0x1F, - (byte) 0xA6, - (byte) 0x8B, - 0x0A, - (byte) 0x81, - 0x12, - (byte) 0xB4, - 0x47, - (byte) 0xAE, - (byte) 0xF3, - 0x4B, - (byte) 0xD8, - (byte) 0xFB, - 0x5A, - 0x7B, - (byte) 0x82, - (byte) 0x9D, - 0x3E, - (byte) 0x86, - 0x23, - 0x71, - (byte) 0xD2, - (byte) 0xCF, - (byte) 0xE5 }; - - assertArrayEquals(ek, encrypted); - - byte[] dek = keyEncryptionKey.unwrapKey("A128KW", ek); - - assertArrayEquals(dek, cek); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("com.azure.security.keyvault.keys.cryptography.TestHelper#getTestParameters") - public void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion) { - byte[] kek = { - 0x00, - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0A, - 0x0B, - 0x0C, - 0x0D, - 0x0E, - 0x0F, - 0x10, - 0x11, - 0x12, - 0x13, - 0x14, - 0x15, - 0x16, - 0x17 }; - - setupSecretKeyAndClient(kek, httpClient, serviceVersion); - - byte[] cek = { - 0x00, - 0x11, - 0x22, - 0x33, - 0x44, - 0x55, - 0x66, - 0x77, - (byte) 0x88, - (byte) 0x99, - (byte) 0xAA, - (byte) 0xBB, - (byte) 0xCC, - (byte) 0xDD, - (byte) 0xEE, - (byte) 0xFF }; - byte[] encrypted = keyEncryptionKey.wrapKey("A192KW", cek); - byte[] ek = { - (byte) 0x96, - 0x77, - (byte) 0x8B, - 0x25, - (byte) 0xAE, - 0x6C, - (byte) 0xA4, - 0x35, - (byte) 0xF9, - 0x2B, - 0x5B, - (byte) 0x97, - (byte) 0xC0, - 0x50, - (byte) 0xAE, - (byte) 0xD2, - 0x46, - (byte) 0x8A, - (byte) 0xB8, - (byte) 0xA1, - 0x7A, - (byte) 0xD8, - 0x4E, - 0x5D }; - - assertArrayEquals(ek, encrypted); - - byte[] dek = keyEncryptionKey.unwrapKey("A192KW", ek); - - assertArrayEquals(dek, cek); - } - - @Test - public void wrapUnwrapSymmetricAK192Local() { - byte[] kek = { - 0x00, - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0A, - 0x0B, - 0x0C, - 0x0D, - 0x0E, - 0x0F, - 0x10, - 0x11, - 0x12, - 0x13, - 0x14, - 0x15, - 0x16, - 0x17 }; - JsonWebKey localKey = JsonWebKey - .fromAes(new SecretKeySpec(kek, "AES"), Arrays.asList(KeyOperation.WRAP_KEY, KeyOperation.UNWRAP_KEY)) - .setId("testKey"); - keyEncryptionKey = setupKeyEncryptionKey(localKey); - byte[] cek = { - 0x00, - 0x11, - 0x22, - 0x33, - 0x44, - 0x55, - 0x66, - 0x77, - (byte) 0x88, - (byte) 0x99, - (byte) 0xAA, - (byte) 0xBB, - (byte) 0xCC, - (byte) 0xDD, - (byte) 0xEE, - (byte) 0xFF }; - byte[] encrypted = keyEncryptionKey.wrapKey("A192KW", cek); - byte[] ek = { - (byte) 0x96, - 0x77, - (byte) 0x8B, - 0x25, - (byte) 0xAE, - 0x6C, - (byte) 0xA4, - 0x35, - (byte) 0xF9, - 0x2B, - 0x5B, - (byte) 0x97, - (byte) 0xC0, - 0x50, - (byte) 0xAE, - (byte) 0xD2, - 0x46, - (byte) 0x8A, - (byte) 0xB8, - (byte) 0xA1, - 0x7A, - (byte) 0xD8, - 0x4E, - 0x5D }; - - assertArrayEquals(ek, encrypted); - - byte[] dek = keyEncryptionKey.unwrapKey("A192KW", ek); - - assertArrayEquals(dek, cek); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTestBase.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTestBase.java deleted file mode 100644 index c75a4010d0f7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClientTestBase.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.BodilessMatcher; -import com.azure.core.test.models.CustomMatcher; -import com.azure.core.test.models.TestProxyRequestMatcher; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Configuration; -import com.azure.identity.AzurePowerShellCredentialBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClientBuilder; -import com.azure.security.keyvault.keys.KeyServiceVersion; -import com.azure.security.keyvault.keys.cryptography.implementation.CryptographyClientImpl; -import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -public abstract class KeyEncryptionKeyClientTestBase extends TestProxyTestBase { - protected boolean isHsmEnabled = false; - protected boolean runManagedHsmTest = false; - - private static final int MAX_RETRIES = 5; - private static final RetryOptions LIVE_RETRY_OPTIONS - = new RetryOptions(new ExponentialBackoffOptions().setMaxRetries(MAX_RETRIES) - .setBaseDelay(Duration.ofSeconds(2)) - .setMaxDelay(Duration.ofSeconds(16))); - - private static final RetryOptions PLAYBACK_RETRY_OPTIONS - = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); - - void beforeTestSetup() { - KeyVaultCredentialPolicy.clearCache(); - } - - KeyEncryptionKeyClientBuilder getKeyEncryptionKeyClientBuilder(HttpClient httpClient, - CryptographyServiceVersion serviceVersion) { - - KeyEncryptionKeyClientBuilder builder = new KeyEncryptionKeyClientBuilder().serviceVersion(serviceVersion) - .credential(getTokenCredentialAndSetMatchers()) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - return interceptorManager.isRecordMode() - ? builder.addPolicy(interceptorManager.getRecordPolicy()) - : builder; - } - } - - KeyClientBuilder getKeyClientBuilder(HttpClient httpClient, String endpoint, KeyServiceVersion serviceVersion) { - - KeyClientBuilder builder = new KeyClientBuilder().vaultUrl(endpoint) - .serviceVersion(serviceVersion) - .credential(getTokenCredentialAndSetMatchers()) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - return interceptorManager.isRecordMode() - ? builder.addPolicy(interceptorManager.getRecordPolicy()) - : builder; - } - } - - CryptographyClientImpl getCryptographyClientImpl(HttpClient httpClient, String keyId, - CryptographyServiceVersion serviceVersion) { - CryptographyClientBuilder builder = new CryptographyClientBuilder().keyIdentifier(keyId) - .serviceVersion(serviceVersion) - .credential(getTokenCredentialAndSetMatchers()) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - if (interceptorManager.isRecordMode()) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - } - - return builder.buildClient().implClient; - } - - private TokenCredential getTokenCredentialAndSetMatchers() { - if (interceptorManager.isLiveMode()) { - return new AzurePowerShellCredentialBuilder().additionallyAllowedTenants("*").build(); - } else if (interceptorManager.isRecordMode()) { - return new DefaultAzureCredentialBuilder().additionallyAllowedTenants("*").build(); - } else { - List customMatchers = new ArrayList<>(); - customMatchers.add(new BodilessMatcher()); - customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); - interceptorManager.addMatchers(customMatchers); - - return new MockTokenCredential(); - } - } - - @Test - public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion); - - @Test - public abstract void wrapUnwrapSymmetricAK128Local(); - - @Test - public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion); - - @Test - public abstract void wrapUnwrapSymmetricAK192Local(); - - public String getEndpoint() { - final String endpoint = runManagedHsmTest - ? Configuration.getGlobalConfiguration() - .get("AZURE_MANAGEDHSM_ENDPOINT", "https://hsmname.managedhsm.azure.net") - : Configuration.getGlobalConfiguration() - .get("AZURE_KEYVAULT_ENDPOINT", "https://vaultname.vault.azure.net"); - Objects.requireNonNull(endpoint); - return endpoint; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/TestHelper.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/TestHelper.java deleted file mode 100644 index e5fb826abfee..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/TestHelper.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.cryptography; - -import com.azure.core.http.HttpClient; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import org.junit.jupiter.params.provider.Arguments; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -import static com.azure.core.test.TestBase.AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL; -import static com.azure.core.test.TestBase.getHttpClients; - -public class TestHelper { - public static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; - private static final String AZURE_KEYVAULT_TEST_CRYPTOGRAPHY_SERVICE_VERSIONS - = "AZURE_KEYVAULT_TEST_CRYPTOGRAPHY_SERVICE_VERSIONS"; - private static final String SERVICE_VERSION_FROM_ENV - = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CRYPTOGRAPHY_SERVICE_VERSIONS); - - /** - * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and - * service versions that should be tested. - * - * @return A stream of HttpClient and service version combinations to test. - */ - static Stream getTestParameters() { - // When this issues is closed, the newer version of junit will have better support for cartesian product of - // arguments - https://github.com/junit-team/junit5/issues/1427 - List argumentsList = new ArrayList<>(); - - getHttpClients().forEach(httpClient -> Arrays.stream(CryptographyServiceVersion.values()) - .filter(TestHelper::shouldServiceVersionBeTested) - .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); - - return argumentsList.stream(); - } - - /** - * Returns whether the given service version match the rules of test framework. - * - *
    - *
  • Using latest service version as default if no environment variable is set.
  • - *
  • If it's set to ALL, all Service versions in {@link CryptographyServiceVersion} will be tested.
  • - *
  • Otherwise, Service version string should match env variable.
  • - *
- * - * Environment values currently supported are: "ALL", "${version}". - * Use comma to separate http clients want to test. - * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} - * - * @param serviceVersion ServiceVersion needs to check. - * - * @return Boolean indicates whether filters out the service version or not. - */ - private static boolean shouldServiceVersionBeTested(CryptographyServiceVersion serviceVersion) { - if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { - return CryptographyServiceVersion.getLatest().equals(serviceVersion); - } - - if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { - return true; - } - - String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); - - return Arrays.stream(configuredServiceVersionList) - .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifierTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifierTest.java deleted file mode 100644 index fb1103e08d69..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/models/KeyVaultKeyIdentifierTest.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.keys.models; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class KeyVaultKeyIdentifierTest { - @Test - void parseWithoutVersion() { - String sourceId = "https://test-key-vault.vault.azure.net/keys/test-key"; - KeyVaultKeyIdentifier keyVaultKeyIdentifier = new KeyVaultKeyIdentifier(sourceId); - - assertEquals(sourceId, keyVaultKeyIdentifier.getSourceId()); - assertEquals("https://test-key-vault.vault.azure.net", keyVaultKeyIdentifier.getVaultUrl()); - assertEquals("test-key", keyVaultKeyIdentifier.getName()); - assertNull(keyVaultKeyIdentifier.getVersion()); - } - - @Test - void parseWithVersion() { - String sourceId = "https://test-key-vault.vault.azure.net/keys/test-key/version"; - KeyVaultKeyIdentifier keyVaultkeyIdentifier = new KeyVaultKeyIdentifier(sourceId); - - assertEquals(sourceId, keyVaultkeyIdentifier.getSourceId()); - assertEquals("https://test-key-vault.vault.azure.net", keyVaultkeyIdentifier.getVaultUrl()); - assertEquals("test-key", keyVaultkeyIdentifier.getName()); - assertEquals("version", keyVaultkeyIdentifier.getVersion()); - } - - @Test - void parseForDeletedKey() { - String sourceId = "https://test-key-vault.vault.azure.net/deletedkeys/test-key"; - KeyVaultKeyIdentifier keyVaultKeyIdentifier = new KeyVaultKeyIdentifier(sourceId); - - assertEquals(sourceId, keyVaultKeyIdentifier.getSourceId()); - assertEquals("https://test-key-vault.vault.azure.net", keyVaultKeyIdentifier.getVaultUrl()); - assertEquals("test-key", keyVaultKeyIdentifier.getName()); - } - - @Test - void parseNullIdentifier() { - assertThrows(NullPointerException.class, () -> new KeyVaultKeyIdentifier(null)); - } - - @Test - void parseInvalidIdentifierWithExtraSegment() { - String sourceId = "https://test-key-vault.vault.azure.net/keys/test-key/version/extra"; - assertThrows(IllegalArgumentException.class, () -> new KeyVaultKeyIdentifier(sourceId)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/swagger/autorest.md b/sdk/keyvault/azure-security-keyvault-keys/swagger/autorest.md deleted file mode 100644 index 92d9427afbf3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/swagger/autorest.md +++ /dev/null @@ -1,84 +0,0 @@ -# Azure Key Vault Keys for Java - -> see https://aka.ms/autorest - -This is the Autorest configuration file for KeyVault Keys. - ---- -## Getting Started -To build the SDK for KeyVault Secrets, simply [Install Autorest](https://aka.ms/autorest) and -in this folder, run: - -> `autorest` - -To see additional help and options, run: - -> `autorest --help` - -### Setup -```ps -npm install -g autorest -``` - -### Generation - -```ps -cd -autorest -``` - -## Configuration - -```yaml -use: '@autorest/java@4.1.42' -output-folder: ../ -java: true -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af9817c15d688c941cda106758045b5deb9a069/specification/keyvault/data-plane/Microsoft.KeyVault/preview/7.6-preview.1/keys.json -title: KeyClient -namespace: com.azure.security.keyvault.keys -models-subpackage: implementation.models -custom-types-subpackage: models -custom-types: KeyCurveName,KeyExportEncryptionAlgorithm,KeyOperation,KeyRotationPolicyAction,KeyType,ReleaseKeyResult -customization-class: src/main/java/KeysCustomizations.java -enable-sync-stack: true -generate-client-as-impl: true -license-header: MICROSOFT_MIT_SMALL -disable-client-builder: true -directive: - - rename-model: - from: KeyReleaseResult - to: ReleaseKeyResult -``` - -### Rename expandable string enum models - -```yaml -directive: - - from: "keys.json" - where: $.definitions - transform: > - $.KeyType = $.JsonWebKey.properties.kty; - $.KeyType["x-ms-enum"].name = "KeyType"; - $.JsonWebKey.properties.kty = { "$ref": "#/definitions/KeyType" }; - $.KeyProperties.properties.kty = { "$ref": "#/definitions/KeyType" }; - $.KeyCreateParameters.properties.kty = { "$ref": "#/definitions/KeyType" }; - - $.KeyCurveName = $.JsonWebKey.properties.crv; - $.KeyCurveName.description = "Elliptic curve name."; - $.KeyCurveName["x-ms-enum"].name = "KeyCurveName"; - $.JsonWebKey.properties.crv = { "$ref": "#/definitions/KeyCurveName" }; - $.KeyProperties.properties.crv = { "$ref": "#/definitions/KeyCurveName" }; - $.KeyCreateParameters.properties.crv = { "$ref": "#/definitions/KeyCurveName" }; - - $.KeyExportEncryptionAlgorithm = $.KeyExportParameters.properties.enc; - $.KeyExportEncryptionAlgorithm["x-ms-enum"].name = "KeyExportEncryptionAlgorithm"; - $.KeyExportParameters.properties.enc = { "$ref": "#/definitions/KeyExportEncryptionAlgorithm" }; - $.KeyReleaseParameters.properties.enc = { "$ref": "#/definitions/KeyExportEncryptionAlgorithm" }; - - $.KeyOperation = $.KeyCreateParameters.properties.key_ops.items; - $.KeyOperation.enum = $.KeyOperation.enum.filter(item => item !== "export"); - $.KeyOperation["x-ms-enum"].name = "KeyOperation"; - $.JsonWebKey.properties.key_ops.items = { "$ref": "#/definitions/KeyOperation" }; - $.KeyCreateParameters.properties.key_ops.items = { "$ref": "#/definitions/KeyOperation" }; - $.KeyUpdateParameters.properties.key_ops.items = { "$ref": "#/definitions/KeyOperation" }; -``` diff --git a/sdk/keyvault/azure-security-keyvault-keys/swagger/pom.xml b/sdk/keyvault/azure-security-keyvault-keys/swagger/pom.xml deleted file mode 100644 index d987bc4d0eb2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/swagger/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - - - com.azure - azure-code-customization-parent - 1.0.0-beta.1 - ../../../parents/azure-code-customization-parent - - - Microsoft Azure Security Key Vault Keys code generation customization - This package contains code generation customization for Microsoft Azure Security Key Vault Keys - - com.azure.tools - azure-security-keyvault-keys-autorest-customization - 1.0.0-beta.1 - jar - diff --git a/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java b/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java deleted file mode 100644 index 88500b428b17..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.ClassCustomization; -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.LibraryCustomization; -import com.azure.autorest.customization.PackageCustomization; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import org.slf4j.Logger; - -/** - * Contains customizations for Azure KeyVault's Keys swagger code generation. - */ -public class KeysCustomizations extends Customization { - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - modelsCustomizations(libraryCustomization.getPackage("com.azure.security.keyvault.keys.models")); - } - - private static void modelsCustomizations(PackageCustomization models) { - models.getClass("KeyCurveName").customizeAst(ast -> ast.getClassByName("KeyCurveName").ifPresent(clazz -> { - clazz.getFieldByName("P256K").ifPresent(field -> field.getVariable(0).setName("P_256K")); - clazz.getFieldByName("P256").ifPresent(field -> field.getVariable(0).setName("P_256")); - clazz.getFieldByName("P384").ifPresent(field -> field.getVariable(0).setName("P_384")); - clazz.getFieldByName("P521").ifPresent(field -> field.getVariable(0).setName("P_521")); - })); - - models.getClass("KeyType").customizeAst(ast -> ast.getClassByName("KeyType").ifPresent(clazz -> { - clazz.getFieldByName("ECHSM").ifPresent(field -> field.getVariable(0).setName("EC_HSM")); - clazz.getFieldByName("RSAHSM").ifPresent(field -> field.getVariable(0).setName("RSA_HSM")); - })); - - models.getClass("KeyExportEncryptionAlgorithm").customizeAst(ast -> ast.getClassByName("KeyExportEncryptionAlgorithm").ifPresent(clazz -> { - clazz.getFieldByName("CKMRSAAESKEYWRAP").ifPresent(field -> field.getVariable(0).setName("CKM_RSA_AES_KEY_WRAP")); - clazz.getFieldByName("RSAAESKEYWRAP256").ifPresent(field -> field.getVariable(0).setName("RSA_AES_KEY_WRAP_256")); - clazz.getFieldByName("RSAAESKEYWRAP384").ifPresent(field -> field.getVariable(0).setName("RSA_AES_KEY_WRAP_384")); - })); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml new file mode 100644 index 000000000000..32886bc46a9e --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml @@ -0,0 +1,5 @@ +directory: specification/keyvault/Security.KeyVault.Keys +commit: 59583521f5e5a5b1e02bd8966bc30b567ecc696a +repo: test-repo-billy/azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common