From 3902f689f05a7bc3e4131b754901112ce273517b Mon Sep 17 00:00:00 2001 From: Pooneh Date: Fri, 19 Aug 2016 12:00:44 -0700 Subject: [PATCH 01/14] Fixed to the key vault certificate feature and tests. 1) getObjests is changed to listObjects 2) Removed getObjectsNext as this is controlled by the library 3) Changes the request parameters for some update* operations to reflect mandatory and optional parameters. 4) Added tests for Async and some additional tests --- .../azure/keyvault/KeyVaultClient.java | 285 +-- .../azure/keyvault/KeyVaultClientImpl.java | 350 ++- .../keyvault/models/CertificateBundle.java | 4 +- .../CertificateIssuerSetParameters.java | 121 + .../CertificateIssuerUpdateParameters.java | 121 + .../keyvault/models/CertificateOperation.java | 4 +- .../CertificateOperationUpdateParameter.java | 45 + .../models/CertificateUpdateParameters.java | 26 + .../azure/keyvault/models/IssuerBundle.java | 4 +- .../azure/keyvault/models/JsonWebKey.java | 5 +- .../azure/keyvault/models/KeyBundle.java | 4 +- .../models/KeyVaultErrorException.java | 11 + .../azure/keyvault/models/SecretBundle.java | 4 +- .../requests/SetCertificateIssuerRequest.java | 110 +- .../UpdateCertificateIssuerRequest.java | 107 +- .../UpdateCertificateOperationRequest.java | 32 +- .../UpdateCertificatePolicyRequest.java | 2 +- .../requests/UpdateCertificateRequest.java | 69 + .../keyvault/test/AsyncOperationsTest.java | 242 ++ .../test/CertificateOperationsTest.java | 2141 ++++++++--------- .../keyvault/test/KeyOperationsTest.java | 166 +- .../KeyVaultClientIntegrationTestBase.java | 12 +- .../keyvault/test/SecretOperationsTest.java | 172 +- 23 files changed, 2383 insertions(+), 1654 deletions(-) create mode 100644 azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java create mode 100644 azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java create mode 100644 azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java create mode 100644 azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java index 52cbba1b6abbe..1c1d45cab33d3 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java @@ -26,7 +26,6 @@ import com.microsoft.azure.keyvault.models.KeyOperationResult; import com.microsoft.azure.keyvault.models.KeyVaultErrorException; import com.microsoft.azure.keyvault.models.KeyVerifyResult; -import com.microsoft.azure.keyvault.models.PageImpl; import com.microsoft.azure.keyvault.models.SecretBundle; import com.microsoft.azure.keyvault.models.SecretItem; import com.microsoft.azure.keyvault.requests.CreateCertificateRequest; @@ -425,7 +424,7 @@ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, S * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getKeyVersions(final String vaultBaseUrl, final String keyName) + public ServiceResponse> listKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName); } @@ -438,7 +437,7 @@ public ServiceResponse> getKeyVersions(final String vaultBase * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final ListOperationCallback serviceCallback) { + public ServiceCall> listKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getKeyVersionsAsync(vaultBaseUrl, keyName, serviceCallback); } /** @@ -452,7 +451,7 @@ public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) + public ServiceResponse> listKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName, maxresults); } @@ -466,7 +465,7 @@ public ServiceResponse> getKeyVersions(final String vaultBase * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getKeyVersionsAsync(vaultBaseUrl, keyName, maxresults, serviceCallback); } @@ -479,7 +478,7 @@ public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getKeys(final String vaultBaseUrl) + public ServiceResponse> listKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeys(vaultBaseUrl); } @@ -491,7 +490,7 @@ public ServiceResponse> getKeys(final String vaultBaseUrl) * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getKeysAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + public ServiceCall> listKeysAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getKeysAsync(vaultBaseUrl, serviceCallback); } /** @@ -504,7 +503,7 @@ public ServiceCall> getKeysAsync(final String vaultBaseUrl, final * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getKeys(final String vaultBaseUrl, final Integer maxresults) + public ServiceResponse> listKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeys(vaultBaseUrl, maxresults); } @@ -517,7 +516,7 @@ public ServiceResponse> getKeys(final String vaultBaseUrl, fi * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getKeysAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listKeysAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getKeysAsync(vaultBaseUrl, maxresults, serviceCallback); } @@ -962,7 +961,7 @@ public ServiceCall getSecretAsync(String vaultBaseUrl, String secr * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getSecrets(final String vaultBaseUrl) + public ServiceResponse> listSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecrets(vaultBaseUrl); } @@ -974,7 +973,7 @@ public ServiceResponse> getSecrets(final String vaultBaseU * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getSecretsAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + public ServiceCall> listSecretsAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getSecretsAsync(vaultBaseUrl, serviceCallback); } /** @@ -987,7 +986,7 @@ public ServiceCall> getSecretsAsync(final String vaultBaseUrl, * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getSecrets(final String vaultBaseUrl, final Integer maxresults) + public ServiceResponse> listSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecrets(vaultBaseUrl, maxresults); } @@ -1000,7 +999,7 @@ public ServiceResponse> getSecrets(final String vaultBaseU * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getSecretsAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listSecretsAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getSecretsAsync(vaultBaseUrl, maxresults, serviceCallback); } @@ -1014,7 +1013,7 @@ public ServiceCall> getSecretsAsync(final String vaultBaseUrl, * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getSecretVersions(final String vaultBaseUrl, final String secretName) + public ServiceResponse> listSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName); } @@ -1027,7 +1026,7 @@ public ServiceResponse> getSecretVersions(final String vau * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final ListOperationCallback serviceCallback) { + public ServiceCall> listSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getSecretVersionsAsync(vaultBaseUrl, secretName, serviceCallback); } /** @@ -1041,7 +1040,7 @@ public ServiceCall> getSecretVersionsAsync(final String vaultBa * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) + public ServiceResponse> listSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName, maxresults); } @@ -1055,7 +1054,7 @@ public ServiceResponse> getSecretVersions(final String vau * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getSecretVersionsAsync(vaultBaseUrl, secretName, maxresults, serviceCallback); } @@ -1068,7 +1067,7 @@ public ServiceCall> getSecretVersionsAsync(final String vaultBa * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificates(final String vaultBaseUrl) + public ServiceResponse> listCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificates(vaultBaseUrl); } @@ -1080,7 +1079,7 @@ public ServiceResponse> getCertificates(final String * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getCertificatesAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + public ServiceCall> listCertificatesAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getCertificatesAsync(vaultBaseUrl, serviceCallback); } /** @@ -1093,7 +1092,7 @@ public ServiceCall> getCertificatesAsync(final String vaul * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificates(final String vaultBaseUrl, final Integer maxresults) + public ServiceResponse> listCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificates(vaultBaseUrl, maxresults); } @@ -1106,7 +1105,7 @@ public ServiceResponse> getCertificates(final String * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getCertificatesAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listCertificatesAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getCertificatesAsync(vaultBaseUrl, maxresults, serviceCallback); } @@ -1223,7 +1222,7 @@ public ServiceCall deleteCertificateContactsAsync(String vaultBaseUrl, * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificateIssuers(final String vaultBaseUrl) + public ServiceResponse> listCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl); } @@ -1235,7 +1234,7 @@ public ServiceResponse> getCertificateIssuers(f * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getCertificateIssuersAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + public ServiceCall> listCertificateIssuersAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getCertificateIssuersAsync(vaultBaseUrl, serviceCallback); } /** @@ -1248,7 +1247,7 @@ public ServiceCall> getCertificateIssuersAsync(final * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) + public ServiceResponse> listCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl, maxresults); } @@ -1261,7 +1260,7 @@ public ServiceResponse> getCertificateIssuers(f * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getCertificateIssuersAsync(vaultBaseUrl, maxresults, serviceCallback); } @@ -1279,8 +1278,11 @@ public ServiceResponse setCertificateIssuer(SetCertificateIssuerRe throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.setCertificateIssuer( setCertificateIssuerRequest.vaultBaseUrl(), - setCertificateIssuerRequest.issuerName(), - setCertificateIssuerRequest.issuer()); + setCertificateIssuerRequest.issuerName(), + setCertificateIssuerRequest.provider(), + setCertificateIssuerRequest.credentials(), + setCertificateIssuerRequest.organizationDetails(), + setCertificateIssuerRequest.attributes()); } /** @@ -1295,7 +1297,10 @@ public ServiceCall setCertificateIssuerAsync(SetCertificateIssuerR return innerKeyVaultClient.setCertificateIssuerAsync( setCertificateIssuerRequest.vaultBaseUrl(), setCertificateIssuerRequest.issuerName(), - setCertificateIssuerRequest.issuer(), + setCertificateIssuerRequest.provider(), + setCertificateIssuerRequest.credentials(), + setCertificateIssuerRequest.organizationDetails(), + setCertificateIssuerRequest.attributes(), serviceCallback); } @@ -1313,8 +1318,11 @@ public ServiceResponse updateCertificateIssuer(UpdateCertificateIs throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateCertificateIssuer( updateCertificateIssuerRequest.vaultBaseUrl(), - updateCertificateIssuerRequest.issuerName(), - updateCertificateIssuerRequest.issuer()); + updateCertificateIssuerRequest.issuerName(), + updateCertificateIssuerRequest.provider(), + updateCertificateIssuerRequest.credentials(), + updateCertificateIssuerRequest.organizationDetails(), + updateCertificateIssuerRequest.attributes()); } /** @@ -1329,8 +1337,11 @@ public ServiceResponse updateCertificateIssuer(UpdateCertificateIs public ServiceCall updateCertificateIssuerAsync(UpdateCertificateIssuerRequest updateCertificateIssuerRequest, final ServiceCallback serviceCallback) { return innerKeyVaultClient.updateCertificateIssuerAsync( updateCertificateIssuerRequest.vaultBaseUrl(), - updateCertificateIssuerRequest.issuerName(), - updateCertificateIssuerRequest.issuer(), + updateCertificateIssuerRequest.issuerName(), + updateCertificateIssuerRequest.provider(), + updateCertificateIssuerRequest.credentials(), + updateCertificateIssuerRequest.organizationDetails(), + updateCertificateIssuerRequest.attributes(), serviceCallback); } @@ -1478,7 +1489,7 @@ public ServiceCall importCertificateAsync(ImportCertificateRe * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificateVersions(final String vaultBaseUrl, final String certificateName) + public ServiceResponse> listCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName); } @@ -1491,7 +1502,7 @@ public ServiceResponse> getCertificateVersions(final * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final ListOperationCallback serviceCallback) { + public ServiceCall> listCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getCertificateVersionsAsync(vaultBaseUrl, certificateName, serviceCallback); } /** @@ -1505,7 +1516,7 @@ public ServiceCall> getCertificateVersionsAsync(final Stri * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) + public ServiceResponse> listCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName, maxresults); } @@ -1519,7 +1530,7 @@ public ServiceResponse> getCertificateVersions(final * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults, final ListOperationCallback serviceCallback) { + public ServiceCall> listCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults, final ListOperationCallback serviceCallback) { return innerKeyVaultClient.getCertificateVersionsAsync(vaultBaseUrl, certificateName, maxresults, serviceCallback); } @@ -1576,7 +1587,7 @@ public ServiceResponse updateCertificatePolicy(UpdateCertific * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall updateCertificatePolicy(UpdateCertificatePolicyRequest updateCertificatePolicyRequest, final ServiceCallback serviceCallback) { + public ServiceCall updateCertificatePolicyAsync(UpdateCertificatePolicyRequest updateCertificatePolicyRequest, final ServiceCallback serviceCallback) { return innerKeyVaultClient.updateCertificatePolicyAsync( updateCertificatePolicyRequest.vaultBaseUrl(), updateCertificatePolicyRequest.certificateName(), @@ -1598,8 +1609,9 @@ public ServiceResponse updateCertificate(UpdateCertificateReq throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateCertificate( updateCertificateRequest.vaultBaseUrl(), - updateCertificateRequest.certificateName(), - updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificateName(), + updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificatePolicy(), updateCertificateRequest.certificateAttributes(), updateCertificateRequest.tags()); } @@ -1616,7 +1628,8 @@ public ServiceCall updateCertificateAsync(UpdateCertificateRe return innerKeyVaultClient.updateCertificateAsync( updateCertificateRequest.vaultBaseUrl(), updateCertificateRequest.certificateName(), - updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificatePolicy(), updateCertificateRequest.certificateAttributes(), updateCertificateRequest.tags(), serviceCallback); @@ -1720,7 +1733,7 @@ public ServiceResponse updateCertificateOperation(UpdateCe return innerKeyVaultClient.updateCertificateOperation( updateCertificateOperationRequest.vaultBaseUrl(), updateCertificateOperationRequest.certificateName(), - updateCertificateOperationRequest.certificateOperation()); + updateCertificateOperationRequest.cancellationRequested()); } /** @@ -1735,7 +1748,7 @@ public ServiceCall updateCertificateOperationAsync(UpdateC return innerKeyVaultClient.updateCertificateOperationAsync( updateCertificateOperationRequest.vaultBaseUrl(), updateCertificateOperationRequest.certificateName(), - updateCertificateOperationRequest.certificateOperation(), + updateCertificateOperationRequest.cancellationRequested(), serviceCallback); } @@ -1789,7 +1802,7 @@ public ServiceResponse deleteCertificateOperation(String v * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - ServiceCall deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + public ServiceCall deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { return innerKeyVaultClient.deleteCertificateOperationAsync(vaultBaseUrl, certificateName, serviceCallback); } @@ -1868,9 +1881,6 @@ public ServiceResponse getPendingCertificateSigningRequest(String vaultB * @return the {@link ServiceCall} object */ public ServiceCall getPendingCertificateSigningRequestAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1901,187 +1911,4 @@ public void onResponse(Call call, Response response) }); return serviceCall; } - - /** - * List the versions of the specified key. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getKeyVersionsNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getKeyVersionsNext(nextPageLink); - } - - /** - * List the versions of the specified key. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getKeyVersionsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getKeyVersionsNextAsync(nextPageLink, serviceCall, serviceCallback); - } - - /** - * List keys in the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getKeysNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getKeysNext(nextPageLink); - } - - /** - * List keys in the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getKeysNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getKeysNextAsync(nextPageLink, serviceCall, serviceCallback); - } - - /** - * List secrets in the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getSecretsNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getSecretsNext(nextPageLink); - } - - /** - * List secrets in the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getSecretsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getSecretsNextAsync(nextPageLink, serviceCall, serviceCallback); - } - - /** - * List the versions of the specified secret. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getSecretVersionsNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getSecretVersionsNext(nextPageLink); - } - - /** - * List the versions of the specified secret. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getSecretVersionsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getSecretVersionsNextAsync(nextPageLink, serviceCall, serviceCallback); - } - - /** - * List certificates in the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getCertificatesNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getCertificatesNext(nextPageLink); - } - - /** - * List certificates in the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getCertificatesNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getCertificatesNextAsync(nextPageLink, serviceCall, serviceCallback); - } - - /** - * List certificate issuers for the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getCertificateIssuersNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getCertificateIssuersNext(nextPageLink); - } - - /** - * List certificate issuers for the specified vault. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getCertificateIssuersNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getCertificateIssuersNextAsync(nextPageLink, serviceCall, serviceCallback); - } - - /** - * List the versions of a certificate. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @throws KeyVaultErrorException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. - */ - public ServiceResponse> getCertificateVersionsNext(final String nextPageLink) - throws KeyVaultErrorException, IOException, IllegalArgumentException { - return innerKeyVaultClient.getCertificateVersionsNext(nextPageLink); - } - - /** - * List the versions of a certificate. - * - * @param nextPageLink The NextLink from the previous successful call to List operation. - * @param serviceCall the ServiceCall object tracking the Retrofit calls - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object - */ - public ServiceCall> getCertificateVersionsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { - return innerKeyVaultClient.getCertificateVersionsNextAsync(nextPageLink, serviceCall, serviceCallback); - } - } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java index 5d3610adf8074..8b5c045ede14a 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java @@ -1,4 +1,8 @@ /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * * Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 * Changes may cause incorrect behavior and will be lost if the code is * regenerated. @@ -17,13 +21,18 @@ import com.microsoft.azure.keyvault.models.CertificateCreateParameters; import com.microsoft.azure.keyvault.models.CertificateImportParameters; import com.microsoft.azure.keyvault.models.CertificateIssuerItem; +import com.microsoft.azure.keyvault.models.CertificateIssuerSetParameters; +import com.microsoft.azure.keyvault.models.CertificateIssuerUpdateParameters; import com.microsoft.azure.keyvault.models.CertificateItem; import com.microsoft.azure.keyvault.models.CertificateMergeParameters; import com.microsoft.azure.keyvault.models.CertificateOperation; +import com.microsoft.azure.keyvault.models.CertificateOperationUpdateParameter; import com.microsoft.azure.keyvault.models.CertificatePolicy; import com.microsoft.azure.keyvault.models.CertificateUpdateParameters; import com.microsoft.azure.keyvault.models.Contacts; +import com.microsoft.azure.keyvault.models.IssuerAttributes; import com.microsoft.azure.keyvault.models.IssuerBundle; +import com.microsoft.azure.keyvault.models.IssuerCredentials; import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyAttributes; import com.microsoft.azure.keyvault.models.KeyBundle; @@ -38,6 +47,7 @@ import com.microsoft.azure.keyvault.models.KeyVaultErrorException; import com.microsoft.azure.keyvault.models.KeyVerifyParameters; import com.microsoft.azure.keyvault.models.KeyVerifyResult; +import com.microsoft.azure.keyvault.models.OrganizationDetails; import com.microsoft.azure.keyvault.models.PageImpl; import com.microsoft.azure.keyvault.models.SecretAttributes; import com.microsoft.azure.keyvault.models.SecretBundle; @@ -342,11 +352,11 @@ interface KeyVaultClientService { @Headers("Content-Type: application/json; charset=utf-8") @PUT("certificates/issuers/{issuer-name}") - Call setCertificateIssuer(@Path("issuer-name") String issuerName, @Body IssuerBundle issuer, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Call setCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateIssuerSetParameters parameter, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("certificates/issuers/{issuer-name}") - Call updateCertificateIssuer(@Path("issuer-name") String issuerName, @Body IssuerBundle issuer, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Call updateCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateIssuerUpdateParameters parameter, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/issuers/{issuer-name}") @@ -386,7 +396,7 @@ interface KeyVaultClientService { @Headers("Content-Type: application/json; charset=utf-8") @PATCH("certificates/{certificate-name}/pending") - Call updateCertificateOperation(@Path("certificate-name") String certificateName, @Body CertificateOperation certificateOperation, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Call updateCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateOperationUpdateParameter certificateOperation, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/{certificate-name}/pending") @@ -1647,7 +1657,7 @@ private ServiceResponse restoreKeyDelegate(Response res * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param keyVersion The version of the key - * @param algorithm algorithm identifier + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization @@ -1687,7 +1697,7 @@ public ServiceResponse encrypt(String vaultBaseUrl, String k * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param keyVersion The version of the key - * @param algorithm algorithm identifier + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object @@ -1750,7 +1760,7 @@ private ServiceResponse encryptDelegate(Response decrypt(String vaultBaseUrl, String k * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param keyVersion The version of the key - * @param algorithm algorithm identifier + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object @@ -1853,7 +1863,7 @@ private ServiceResponse decryptDelegate(Response sign(String vaultBaseUrl, String keyN * @param vaultBaseUrl The vault name, e.g. 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 algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object @@ -1956,7 +1966,7 @@ private ServiceResponse signDelegate(Response * @param vaultBaseUrl The vault name, e.g. 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 algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' * @param digest The digest used for signing * @param signature The signature to be verified * @throws KeyVaultErrorException exception thrown from REST call @@ -2001,7 +2011,7 @@ public ServiceResponse verify(String vaultBaseUrl, String keyNa * @param vaultBaseUrl The vault name, e.g. 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 algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' * @param digest The digest used for signing * @param signature The signature to be verified * @param serviceCallback the async ServiceCallback to handle successful and failed responses. @@ -2069,7 +2079,7 @@ private ServiceResponse verifyDelegate(Response r * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param keyVersion The version of the key - * @param algorithm algorithm identifier + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization @@ -2109,7 +2119,7 @@ public ServiceResponse wrapKey(String vaultBaseUrl, String k * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param keyVersion The version of the key - * @param algorithm algorithm identifier + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object @@ -2172,7 +2182,7 @@ private ServiceResponse wrapKeyDelegate(Response unwrapKey(String vaultBaseUrl, String * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param keyVersion The version of the key - * @param algorithm algorithm identifier + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object @@ -3712,28 +3722,35 @@ private ServiceResponse> getCertificateIssuersDe * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param issuer The issuer bundle. + * @param provider The name of the issuer. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, IssuerBundle issuer) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (issuerName == null) { throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } - if (issuer == null) { - throw new IllegalArgumentException("Parameter issuer is required and cannot be null."); - } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - Validator.validate(issuer); + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); + parameter.withProvider(provider); + parameter.withCredentials(null); + parameter.withOrganizationDetails(null); + parameter.withAttributes(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateIssuer(issuerName, issuer, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); + Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); return setCertificateIssuerDelegate(call.execute()); } @@ -3742,26 +3759,129 @@ public ServiceResponse setCertificateIssuer(String vaultBaseUrl, S * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param issuer The issuer bundle. + * @param provider The name of the issuer. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ - public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, IssuerBundle issuer, final ServiceCallback serviceCallback) { + public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback serviceCallback) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (issuerName == null) { + throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); + parameter.withProvider(provider); + parameter.withCredentials(null); + parameter.withOrganizationDetails(null); + parameter.withAttributes(null); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); + final ServiceCall serviceCall = new ServiceCall<>(call); + call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + ServiceResponse clientResponse = setCertificateIssuerDelegate(response); + if (serviceCallback != null) { + serviceCallback.success(clientResponse); + } + serviceCall.success(clientResponse); + } catch (KeyVaultErrorException | IOException exception) { + if (serviceCallback != null) { + serviceCallback.failure(exception); + } + serviceCall.failure(exception); + } + } + }); + return serviceCall; + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The name of the issuer. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @throws KeyVaultErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (issuerName == null) { throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } - if (issuer == null) { - throw new IllegalArgumentException("Parameter issuer is required and cannot be null."); + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + Validator.validate(credentials); + Validator.validate(organizationDetails); + Validator.validate(attributes); + CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); + parameter.withProvider(provider); + parameter.withCredentials(credentials); + parameter.withOrganizationDetails(organizationDetails); + parameter.withAttributes(attributes); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); + return setCertificateIssuerDelegate(call.execute()); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The name of the issuer. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link Call} object + */ + public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (issuerName == null) { + throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - Validator.validate(issuer); + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + Validator.validate(credentials); + Validator.validate(organizationDetails); + Validator.validate(attributes); + CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); + parameter.withProvider(provider); + parameter.withCredentials(credentials); + parameter.withOrganizationDetails(organizationDetails); + parameter.withAttributes(attributes); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateIssuer(issuerName, issuer, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); + Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); final ServiceCall serviceCall = new ServiceCall<>(call); call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { @Override @@ -3795,28 +3915,35 @@ private ServiceResponse setCertificateIssuerDelegate(Response updateCertificateIssuer(String vaultBaseUrl, String issuerName, IssuerBundle issuer) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public ServiceResponse updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (issuerName == null) { throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } - if (issuer == null) { - throw new IllegalArgumentException("Parameter issuer is required and cannot be null."); - } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - Validator.validate(issuer); + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(provider); + parameter.withCredentials(null); + parameter.withOrganizationDetails(null); + parameter.withAttributes(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateIssuer(issuerName, issuer, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); + Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); return updateCertificateIssuerDelegate(call.execute()); } @@ -3825,26 +3952,129 @@ public ServiceResponse updateCertificateIssuer(String vaultBaseUrl * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param issuer The issuer bundle. + * @param provider The name of the issuer. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ - public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, IssuerBundle issuer, final ServiceCallback serviceCallback) { + public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback serviceCallback) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (issuerName == null) { + throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(provider); + parameter.withCredentials(null); + parameter.withOrganizationDetails(null); + parameter.withAttributes(null); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); + final ServiceCall serviceCall = new ServiceCall<>(call); + call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + ServiceResponse clientResponse = updateCertificateIssuerDelegate(response); + if (serviceCallback != null) { + serviceCallback.success(clientResponse); + } + serviceCall.success(clientResponse); + } catch (KeyVaultErrorException | IOException exception) { + if (serviceCallback != null) { + serviceCallback.failure(exception); + } + serviceCall.failure(exception); + } + } + }); + return serviceCall; + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The name of the issuer. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @throws KeyVaultErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (issuerName == null) { throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } - if (issuer == null) { - throw new IllegalArgumentException("Parameter issuer is required and cannot be null."); + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + Validator.validate(credentials); + Validator.validate(organizationDetails); + Validator.validate(attributes); + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(provider); + parameter.withCredentials(credentials); + parameter.withOrganizationDetails(organizationDetails); + parameter.withAttributes(attributes); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); + return updateCertificateIssuerDelegate(call.execute()); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The name of the issuer. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link Call} object + */ + public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (issuerName == null) { + throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - Validator.validate(issuer); + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + Validator.validate(credentials); + Validator.validate(organizationDetails); + Validator.validate(attributes); + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(provider); + parameter.withCredentials(credentials); + parameter.withOrganizationDetails(organizationDetails); + parameter.withAttributes(attributes); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateIssuer(issuerName, issuer, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); + Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); final ServiceCall serviceCall = new ServiceCall<>(call); call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { @Override @@ -4742,9 +4972,11 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } + final CertificatePolicy certificatePolicy = null; final CertificateAttributes certificateAttributes = null; final Map tags = null; CertificateUpdateParameters parameters = new CertificateUpdateParameters(); + parameters.withCertificatePolicy(null); parameters.withCertificateAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); @@ -4774,9 +5006,11 @@ public ServiceCall updateCertificateAsync(String vaultBaseUrl if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } + final CertificatePolicy certificatePolicy = null; final CertificateAttributes certificateAttributes = null; final Map tags = null; CertificateUpdateParameters parameters = new CertificateUpdateParameters(); + parameters.withCertificatePolicy(null); parameters.withCertificateAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); @@ -4808,6 +5042,7 @@ public void onResponse(Call call, Response response) * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate in the given vault * @param certificateVersion The version of the certificate + * @param certificatePolicy The management policy for the certificate * @param certificateAttributes The attributes of the certificate (optional) * @param tags Application-specific metadata in the form of key-value pairs * @throws KeyVaultErrorException exception thrown from REST call @@ -4815,7 +5050,7 @@ public void onResponse(Call call, Response response) * @throws IllegalArgumentException exception thrown from invalid parameters * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public ServiceResponse updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4828,9 +5063,11 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } + Validator.validate(certificatePolicy); Validator.validate(certificateAttributes); Validator.validate(tags); CertificateUpdateParameters parameters = new CertificateUpdateParameters(); + parameters.withCertificatePolicy(certificatePolicy); parameters.withCertificateAttributes(certificateAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); @@ -4844,12 +5081,13 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate in the given vault * @param certificateVersion The version of the certificate + * @param certificatePolicy The management policy for the certificate * @param certificateAttributes The attributes of the certificate (optional) * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ - public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4862,9 +5100,11 @@ public ServiceCall updateCertificateAsync(String vaultBaseUrl if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } + Validator.validate(certificatePolicy); Validator.validate(certificateAttributes); Validator.validate(tags); CertificateUpdateParameters parameters = new CertificateUpdateParameters(); + parameters.withCertificatePolicy(certificatePolicy); parameters.withCertificateAttributes(certificateAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); @@ -4983,28 +5223,26 @@ private ServiceResponse getCertificateDelegate(Response updateCertificateOperation(String vaultBaseUrl, String certificateName, CertificateOperation certificateOperation) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public ServiceResponse updateCertificateOperation(String vaultBaseUrl, String certificateName, boolean cancellationRequested) throws KeyVaultErrorException, IOException, IllegalArgumentException { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (certificateName == null) { throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); } - if (certificateOperation == null) { - throw new IllegalArgumentException("Parameter certificateOperation is required and cannot be null."); - } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - Validator.validate(certificateOperation); + CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); + certificateOperation.withCancellationRequested(cancellationRequested); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateOperation(certificateName, certificateOperation, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); + Call call = service.updateCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), certificateOperation, parameterizedHost, this.userAgent()); return updateCertificateOperationDelegate(call.execute()); } @@ -5013,26 +5251,24 @@ public ServiceResponse updateCertificateOperation(String v * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate - * @param certificateOperation The certificate operation response. + * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ - public ServiceCall updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, CertificateOperation certificateOperation, final ServiceCallback serviceCallback) { + public ServiceCall updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested, final ServiceCallback serviceCallback) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (certificateName == null) { throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); } - if (certificateOperation == null) { - throw new IllegalArgumentException("Parameter certificateOperation is required and cannot be null."); - } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - Validator.validate(certificateOperation); + CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); + certificateOperation.withCancellationRequested(cancellationRequested); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateOperation(certificateName, certificateOperation, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); + Call call = service.updateCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), certificateOperation, parameterizedHost, this.userAgent()); final ServiceCall serviceCall = new ServiceCall<>(call); call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { @Override diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java index eda7dfbc9da3a..44417b1eea285 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java @@ -13,6 +13,7 @@ import com.microsoft.azure.keyvault.CertificateIdentifier; import com.microsoft.azure.keyvault.KeyIdentifier; import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; import com.microsoft.rest.Base64Url; import java.io.IOException; @@ -239,7 +240,8 @@ public KeyIdentifier keyIdentifier() { @Override public String toString() { - ObjectMapper mapper = new ObjectMapper(); + AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); + ObjectMapper mapper = mapperAdapter.getObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java new file mode 100644 index 0000000000000..f9daf44e44fda --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The certificate issuer set parameters. + */ +public class CertificateIssuerSetParameters { + /** + * The name of the issuer. + */ + @JsonProperty(required = true) + private String provider; + + /** + * The credentials to be used for the issuer. + */ + private IssuerCredentials credentials; + + /** + * Details of the organization as provided to the issuer. + */ + @JsonProperty(value = "org_details") + private OrganizationDetails organizationDetails; + + /** + * Attributes of the issuer object. + */ + private IssuerAttributes attributes; + + /** + * Get the provider value. + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Set the provider value. + * + * @param provider the provider value to set + * @return the CertificateIssuerSetParameters object itself. + */ + public CertificateIssuerSetParameters withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get the credentials value. + * + * @return the credentials value + */ + public IssuerCredentials credentials() { + return this.credentials; + } + + /** + * Set the credentials value. + * + * @param credentials the credentials value to set + * @return the CertificateIssuerSetParameters object itself. + */ + public CertificateIssuerSetParameters withCredentials(IssuerCredentials credentials) { + this.credentials = credentials; + return this; + } + + /** + * Get the organizationDetails value. + * + * @return the organizationDetails value + */ + public OrganizationDetails organizationDetails() { + return this.organizationDetails; + } + + /** + * Set the organizationDetails value. + * + * @param organizationDetails the organizationDetails value to set + * @return the CertificateIssuerSetParameters object itself. + */ + public CertificateIssuerSetParameters withOrganizationDetails(OrganizationDetails organizationDetails) { + this.organizationDetails = organizationDetails; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public IssuerAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the CertificateIssuerSetParameters object itself. + */ + public CertificateIssuerSetParameters withAttributes(IssuerAttributes attributes) { + this.attributes = attributes; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java new file mode 100644 index 0000000000000..7af311457b0ea --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The certificate issuer set parameters. + */ +public class CertificateIssuerUpdateParameters { + /** + * The name of the issuer. + */ + @JsonProperty(required = true) + private String provider; + + /** + * The credentials to be used for the issuer. + */ + private IssuerCredentials credentials; + + /** + * Details of the organization as provided to the issuer. + */ + @JsonProperty(value = "org_details") + private OrganizationDetails organizationDetails; + + /** + * Attributes of the issuer object. + */ + private IssuerAttributes attributes; + + /** + * Get the provider value. + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Set the provider value. + * + * @param provider the provider value to set + * @return the CertificateIssuerUpdateParameters object itself. + */ + public CertificateIssuerUpdateParameters withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get the credentials value. + * + * @return the credentials value + */ + public IssuerCredentials credentials() { + return this.credentials; + } + + /** + * Set the credentials value. + * + * @param credentials the credentials value to set + * @return the CertificateIssuerUpdateParameters object itself. + */ + public CertificateIssuerUpdateParameters withCredentials(IssuerCredentials credentials) { + this.credentials = credentials; + return this; + } + + /** + * Get the organizationDetails value. + * + * @return the organizationDetails value + */ + public OrganizationDetails organizationDetails() { + return this.organizationDetails; + } + + /** + * Set the organizationDetails value. + * + * @param organizationDetails the organizationDetails value to set + * @return the CertificateIssuerUpdateParameters object itself. + */ + public CertificateIssuerUpdateParameters withOrganizationDetails(OrganizationDetails organizationDetails) { + this.organizationDetails = organizationDetails; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public IssuerAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the CertificateIssuerUpdateParameters object itself. + */ + public CertificateIssuerUpdateParameters withAttributes(IssuerAttributes attributes) { + this.attributes = attributes; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java index c8aea174e4bf3..02fd132ae9754 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java @@ -17,6 +17,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.CertificateOperationIdentifier; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; /** * A certificate operation is returned in case of async requests. @@ -255,7 +256,8 @@ public CertificateOperationIdentifier certificateOperationIdentifier() { @Override public String toString() { - ObjectMapper mapper = new ObjectMapper(); + AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); + ObjectMapper mapper = mapperAdapter.getObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java new file mode 100644 index 0000000000000..dd7c42a5f4ac0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A certificate operation is returned in case of async requests. + */ +public class CertificateOperationUpdateParameter { + /** + * Indicates if cancellation was requested on the certificate operation. + */ + @JsonProperty(value = "cancellation_requested", required = true) + private boolean cancellationRequested; + + /** + * Get the cancellationRequested value. + * + * @return the cancellationRequested value + */ + public boolean cancellationRequested() { + return this.cancellationRequested; + } + + /** + * Set the cancellationRequested value. + * + * @param cancellationRequested the cancellationRequested value to set + * @return the CertificateOperationUpdateParameter object itself. + */ + public CertificateOperationUpdateParameter withCancellationRequested(boolean cancellationRequested) { + this.cancellationRequested = cancellationRequested; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java index 0e3d426eed6cf..e3e899ff572c6 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java @@ -17,6 +17,12 @@ * The certificate update parameters. */ public class CertificateUpdateParameters { + /** + * The management policy for the certificate. + */ + @JsonProperty(value = "policy") + private CertificatePolicy certificatePolicy; + /** * The attributes of the certificate (optional). */ @@ -28,6 +34,26 @@ public class CertificateUpdateParameters { */ private Map tags; + /** + * Get the certificatePolicy value. + * + * @return the certificatePolicy value + */ + public CertificatePolicy certificatePolicy() { + return this.certificatePolicy; + } + + /** + * Set the certificatePolicy value. + * + * @param certificatePolicy the certificatePolicy value to set + * @return the CertificateUpdateParameters object itself. + */ + public CertificateUpdateParameters withCertificatePolicy(CertificatePolicy certificatePolicy) { + this.certificatePolicy = certificatePolicy; + return this; + } + /** * Get the certificateAttributes value. * diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java index 3dd318e5139f8..e30c98684da69 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java @@ -17,6 +17,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.IssuerIdentifier; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; /** * The issuer for Key Vault certificate. @@ -151,7 +152,8 @@ public IssuerIdentifier issuerIdentifier() { @Override public String toString() { - ObjectMapper mapper = new ObjectMapper(); + AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); + ObjectMapper mapper = mapperAdapter.getObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java index ed9bb700c1543..ef267481ebba1 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java @@ -29,6 +29,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; import com.microsoft.rest.Base64Url; /** @@ -95,7 +96,6 @@ public class JsonWebKey { /** * Symmetric key. */ - @JsonProperty(value = "K") private Base64Url k; /** @@ -436,7 +436,8 @@ public JsonWebKey withT(byte[] t) { @Override public String toString() { - ObjectMapper mapper = new ObjectMapper(); + AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); + ObjectMapper mapper = mapperAdapter.getObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java index 4c13b1490a64d..453e5177fab2b 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java @@ -17,6 +17,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.KeyIdentifier; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; /** * A KeyBundle consisting of a WebKey plus its Attributes. @@ -110,7 +111,8 @@ public KeyIdentifier keyIdentifier() { @Override public String toString() { - ObjectMapper mapper = new ObjectMapper(); + AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); + ObjectMapper mapper = mapperAdapter.getObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java index bdcfc617fc14c..43b6a45e162db 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java @@ -29,6 +29,17 @@ public class KeyVaultErrorException extends RestException { * Initializes a new instance of the KeyVaultErrorException class. */ public KeyVaultErrorException() { } + + @Override + public String getMessage() + { + if(body != null && body.error() != null + && body.error().message() != null + && !body.error().message().isEmpty()) { + return body.error().message(); + } + return getMessage(); + } /** * Initializes a new instance of the KeyVaultErrorException class. * diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java index 52d7e736fb451..c52baf76b82f9 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java @@ -17,6 +17,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; /** * A Secret consisting of a value, id and its attributes. @@ -185,7 +186,8 @@ public SecretIdentifier secretIdentifier() { @Override public String toString() { - ObjectMapper mapper = new ObjectMapper(); + AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); + ObjectMapper mapper = mapperAdapter.getObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java index 5c2d00f4d82e6..23201a4a26f4a 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java @@ -1,7 +1,11 @@ package com.microsoft.azure.keyvault.requests; +import java.util.ArrayList; + +import com.microsoft.azure.keyvault.models.AdministratorDetails; import com.microsoft.azure.keyvault.models.IssuerAttributes; -import com.microsoft.azure.keyvault.models.IssuerBundle; +import com.microsoft.azure.keyvault.models.IssuerCredentials; +import com.microsoft.azure.keyvault.models.OrganizationDetails; /** * The set certificate issuer request class. @@ -10,7 +14,10 @@ public final class SetCertificateIssuerRequest { private final String vaultBaseUrl; private final String issuerName; - private final IssuerBundle issuer; + private final String provider; + private final IssuerCredentials credentials; + private final OrganizationDetails organizationDetails; + private final IssuerAttributes attributes; /** * The {@link SetCertificateIssuerRequest} builder. @@ -20,9 +27,12 @@ public static class Builder { // Required parameters private final String vaultBaseUrl; private final String issuerName; + private final String provider; // Optional parameters - private IssuerBundle issuer; + private IssuerCredentials credentials; + private OrganizationDetails organizationDetails; + private IssuerAttributes attributes; /** * The builder for constructing {@link SetCertificateIssuerRequest} @@ -32,24 +42,50 @@ public static class Builder { * The vault name, e.g. https://myvault.vault.azure.net. * @param issuerName * The name of the issuer. + * @param provider The name of the issuer. */ - public Builder(String vaultBaseUrl, String issuerName) { + public Builder(String vaultBaseUrl, String issuerName, String provider) { this.vaultBaseUrl = vaultBaseUrl; this.issuerName = issuerName; + this.provider = provider; } /** - * Set the issuer value. + * Set issuer credentials. * - * @param issuer - * The issuer bundle. + * @param credentials + * The issuer credentials. * @return the Builder object itself. */ - public Builder withIssuer(IssuerBundle issuer) { - this.issuer = issuer; + public Builder withCredentials(IssuerCredentials credentials) { + this.credentials = credentials; return this; } - + + /** + * Set issuer organization details. + * + * @param organizationDetails + * The issuer organization details. + * @return the Builder object itself. + */ + public Builder withOrganizationDetails(OrganizationDetails organizationDetails) { + this.organizationDetails = organizationDetails; + return this; + } + + /** + * Set issuer attributes. + * + * @param organizationDetails + * The issuer attributes. + * @return the Builder object itself. + */ + public Builder withAttributes(IssuerAttributes attributes) { + this.attributes = attributes; + return this; + } + /** * builds the {@link SetCertificateIssuerRequest} object. * @@ -63,15 +99,25 @@ public SetCertificateIssuerRequest build() { private SetCertificateIssuerRequest(Builder builder) { vaultBaseUrl = builder.vaultBaseUrl; issuerName = builder.issuerName; - if (builder.issuer != null) { - issuer = new IssuerBundle().withProvider(builder.issuer.provider()) - .withOrganizationDetails(builder.issuer.organizationDetails()) - .withCredentials(builder.issuer.credentials()); - if (builder.issuer.attributes() != null) { - issuer.withAttributes(new IssuerAttributes().withEnabled(builder.issuer.attributes().enabled())); - } + provider = builder.provider; + if(builder.organizationDetails != null) { + organizationDetails = new OrganizationDetails() + .withId(builder.organizationDetails.id()) + .withAdminDetails(new ArrayList(builder.organizationDetails.adminDetails())); } else { - issuer = null; + organizationDetails = null; + } + if(builder.credentials != null) { + credentials = new IssuerCredentials() + .withAccountId(builder.credentials.accountId()) + .withPassword(builder.credentials.password()); + } else { + credentials = null; + } + if (builder.attributes != null) { + attributes = new IssuerAttributes().withEnabled(builder.attributes.enabled()); + } else { + attributes = null; } } @@ -90,10 +136,30 @@ public String issuerName() { } /** - * @return the issuer + * @return the issuer provider name */ - public IssuerBundle issuer() { - return issuer; + public String provider() { + return provider; + } + + /** + * @return the issuer credentials + */ + public IssuerCredentials credentials() { + return credentials; + } + + /** + * @return the organization details + */ + public OrganizationDetails organizationDetails() { + return organizationDetails; + } + + /** + * @return the issuer attributes + */ + public IssuerAttributes attributes() { + return attributes; } - } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java index 633d16a2e7a70..37d1048673aea 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java @@ -1,7 +1,11 @@ package com.microsoft.azure.keyvault.requests; +import java.util.ArrayList; + +import com.microsoft.azure.keyvault.models.AdministratorDetails; import com.microsoft.azure.keyvault.models.IssuerAttributes; -import com.microsoft.azure.keyvault.models.IssuerBundle; +import com.microsoft.azure.keyvault.models.IssuerCredentials; +import com.microsoft.azure.keyvault.models.OrganizationDetails; /** * The update certificate issuer request class. @@ -9,7 +13,10 @@ public final class UpdateCertificateIssuerRequest { private final String vaultBaseUrl; private final String issuerName; - private final IssuerBundle issuer; + private final String provider; + private final IssuerCredentials credentials; + private final OrganizationDetails organizationDetails; + private final IssuerAttributes attributes; /** * The {@link UpdateCertificateIssuerRequest} builder. @@ -19,9 +26,12 @@ public static class Builder { // Required parameters private final String vaultBaseUrl; private final String issuerName; + private final String provider; // Optional parameters - private IssuerBundle issuer; + private IssuerCredentials credentials; + private OrganizationDetails organizationDetails; + private IssuerAttributes attributes; /** * The builder for constructing {@link UpdateCertificateIssuerRequest} @@ -32,20 +42,45 @@ public static class Builder { * @param issuerName * The name of the issuer in the given vault. */ - public Builder(String vaultBaseUrl, String issuerName) { + public Builder(String vaultBaseUrl, String issuerName, String provider) { this.vaultBaseUrl = vaultBaseUrl; this.issuerName = issuerName; + this.provider = provider; } /** - * Set the issuer value. + * Set issuer credentials. + * + * @param credentials + * The issuer credentials. + * @return the Builder object itself. + */ + public Builder withCredentials(IssuerCredentials credentials) { + this.credentials = credentials; + return this; + } + + /** + * Set issuer organization details. * - * @param issuer - * The issuer bundle. + * @param organizationDetails + * The issuer organization details. * @return the Builder object itself. */ - public Builder withIssuer(IssuerBundle issuer) { - this.issuer = issuer; + public Builder withOrganizationDetails(OrganizationDetails organizationDetails) { + this.organizationDetails = organizationDetails; + return this; + } + + /** + * Set issuer attributes. + * + * @param organizationDetails + * The issuer attributes. + * @return the Builder object itself. + */ + public Builder withAttributes(IssuerAttributes attributes) { + this.attributes = attributes; return this; } @@ -62,16 +97,25 @@ public UpdateCertificateIssuerRequest build() { private UpdateCertificateIssuerRequest(Builder builder) { vaultBaseUrl = builder.vaultBaseUrl; issuerName = builder.issuerName; - - if (builder.issuer != null) { - issuer = new IssuerBundle().withProvider(builder.issuer.provider()) - .withOrganizationDetails(builder.issuer.organizationDetails()) - .withCredentials(builder.issuer.credentials()); - if (builder.issuer.attributes() != null) { - issuer.withAttributes(new IssuerAttributes().withEnabled(builder.issuer.attributes().enabled())); - } + provider = builder.provider; + if(builder.organizationDetails != null) { + organizationDetails = new OrganizationDetails() + .withId(builder.organizationDetails.id()) + .withAdminDetails(new ArrayList(builder.organizationDetails.adminDetails())); } else { - issuer = null; + organizationDetails = null; + } + if(builder.credentials != null) { + credentials = new IssuerCredentials() + .withAccountId(builder.credentials.accountId()) + .withPassword(builder.credentials.password()); + } else { + credentials = null; + } + if (builder.attributes != null) { + attributes = new IssuerAttributes().withEnabled(builder.attributes.enabled()); + } else { + attributes = null; } } @@ -90,9 +134,30 @@ public String issuerName() { } /** - * @return the issuer + * @return the issuer provider name + */ + public String provider() { + return provider; + } + + /** + * @return the issuer credentials + */ + public IssuerCredentials credentials() { + return credentials; + } + + /** + * @return the organization details + */ + public OrganizationDetails organizationDetails() { + return organizationDetails; + } + + /** + * @return the issuer attributes */ - public IssuerBundle issuer() { - return issuer; + public IssuerAttributes attributes() { + return attributes; } } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java index 95bd2af87a2e7..24f68899e111c 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java @@ -1,14 +1,12 @@ package com.microsoft.azure.keyvault.requests; -import com.microsoft.azure.keyvault.models.CertificateOperation; - /** * The update certificate operation request class. */ public final class UpdateCertificateOperationRequest { private final String vaultBaseUrl; private final String certificateName; - private final CertificateOperation certificateOperation; + private final Boolean cancellationRequested; /** * The {@link UpdateCertificateOperationRequest} builder. @@ -18,9 +16,9 @@ public static class Builder { // Required parameters private final String vaultBaseUrl; private final String certificateName; + private final Boolean cancellationRequested; // Optional parameters - private Boolean cancellationRequested; /** * The builder for constructing {@link CreateCertificateRequest} object. @@ -29,23 +27,13 @@ public static class Builder { * The vault name, e.g. https://myvault.vault.azure.net. * @param certificateName * The name of the certificate in the given vault. + * @param cancellationRequested + * Indicates if cancellation was requested on the certificate operation. */ - public Builder(String vaultBaseUrl, String certificateName) { + public Builder(String vaultBaseUrl, String certificateName, Boolean cancellationRequested) { this.vaultBaseUrl = vaultBaseUrl; this.certificateName = certificateName; - } - - /** - * Set the cancellationRequested value. - * - * @param cancellationRequested - * Indicates if cancellation was requested on the certificate - * operation. - * @return the Builder object itself. - */ - public Builder withCancellationRequested(Boolean cancellationRequested) { this.cancellationRequested = cancellationRequested; - return this; } /** @@ -61,11 +49,7 @@ public UpdateCertificateOperationRequest build() { private UpdateCertificateOperationRequest(Builder builder) { vaultBaseUrl = builder.vaultBaseUrl; certificateName = builder.certificateName; - if (builder.cancellationRequested != null) { - certificateOperation = new CertificateOperation().withCancellationRequested(builder.cancellationRequested); - } else { - certificateOperation = null; - } + cancellationRequested = builder.cancellationRequested; } /** @@ -85,7 +69,7 @@ public String certificateName() { /** * @return the certificate policy */ - public CertificateOperation certificateOperation() { - return certificateOperation; + public Boolean cancellationRequested() { + return cancellationRequested; } } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java index da062e1ca5220..ea155328ece75 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java @@ -106,7 +106,7 @@ private UpdateCertificatePolicyRequest(Builder builder) { new SecretProperties().withContentType(builder.policy.secretProperties().contentType())); } } else { - certificatePolicy = null; + certificatePolicy = new CertificatePolicy(); } } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java index 009caeded6ce7..407b4c1407d27 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java @@ -1,9 +1,17 @@ package com.microsoft.azure.keyvault.requests; +import java.util.ArrayList; import java.util.Collections; import java.util.Map; import com.microsoft.azure.keyvault.models.CertificateAttributes; +import com.microsoft.azure.keyvault.models.CertificatePolicy; +import com.microsoft.azure.keyvault.models.IssuerReference; +import com.microsoft.azure.keyvault.models.KeyProperties; +import com.microsoft.azure.keyvault.models.LifetimeAction; +import com.microsoft.azure.keyvault.models.SecretProperties; +import com.microsoft.azure.keyvault.models.X509CertificateProperties; +import com.microsoft.azure.keyvault.requests.CreateCertificateRequest.Builder; /** * The update certificate request class. @@ -12,6 +20,7 @@ public final class UpdateCertificateRequest { private final String vaultBaseUrl; private final String certificateName; private final String certificateVersion; + private final CertificatePolicy certificatePolicy; private final CertificateAttributes certificateAttributes; private final Map tags; @@ -28,6 +37,7 @@ public static class Builder { private String certificateVersion; private CertificateAttributes attributes; private Map tags; + private CertificatePolicy policy; /** * The builder for constructing {@link UpdateCertificateRequest} object. @@ -53,6 +63,19 @@ public Builder withCertificateVersion(String version) { this.certificateVersion = version; return this; } + + /** + * Set the certificatePolicy value. Mandatory if sending the create + * request for the first time. + * + * @param certificatePolicy + * The management policy for the certificate. + * @return the Builder object itself. + */ + public Builder withPolicy(CertificatePolicy certificatePolicy) { + this.policy = certificatePolicy; + return this; + } /** * Set the attributes value. @@ -107,6 +130,45 @@ private UpdateCertificateRequest(Builder builder) { } else { tags = null; } + + if (builder.policy != null) { + certificatePolicy = new CertificatePolicy(); + if (builder.policy.attributes() != null) { + certificatePolicy.withAttributes((CertificateAttributes) new CertificateAttributes() + .withEnabled(builder.policy.attributes().enabled()) + .withExpires(builder.policy.attributes().expires()) + .withNotBefore(builder.policy.attributes().notBefore())); + } + if (builder.policy.issuerReference() != null) { + certificatePolicy + .withIssuerReference(new IssuerReference().withName(builder.policy.issuerReference().name())); + } + if (builder.policy.x509CertificateProperties() != null) { + certificatePolicy.withX509CertificateProperties(new X509CertificateProperties() + .withValidityInMonths(builder.policy.x509CertificateProperties().validityInMonths()) + .withSubjectAlternativeNames( + builder.policy.x509CertificateProperties().subjectAlternativeNames()) + .withSubject(builder.policy.x509CertificateProperties().subject()) + .withEkus(builder.policy.x509CertificateProperties().ekus()) + .withKeyUsage(builder.policy.x509CertificateProperties().keyUsage())); + } + if (builder.policy.lifetimeActions() != null) { + certificatePolicy.withLifetimeActions(new ArrayList(builder.policy.lifetimeActions())); + } + if (builder.policy.keyProperties() != null) { + certificatePolicy.withKeyProperties( + new KeyProperties().withExportable(builder.policy.keyProperties().exportable()) + .withKeySize(builder.policy.keyProperties().keySize()) + .withKeyType(builder.policy.keyProperties().keyType()) + .withReuseKey(builder.policy.keyProperties().reuseKey())); + } + if (builder.policy.secretProperties() != null) { + certificatePolicy.withSecretProperties( + new SecretProperties().withContentType(builder.policy.secretProperties().contentType())); + } + } else { + certificatePolicy = new CertificatePolicy(); + } } /** @@ -130,6 +192,13 @@ public String certificateVersion() { return certificateVersion; } + /** + * @return the certificate policy + */ + public CertificatePolicy certificatePolicy() { + return certificatePolicy; + } + /** * @return the certificate attributes */ diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java new file mode 100644 index 0000000000000..86410c9ab946f --- /dev/null +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -0,0 +1,242 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.test; + +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import org.junit.Assert; +import org.junit.Test; + +import com.microsoft.azure.keyvault.models.BackupKeyResult; +import com.microsoft.azure.keyvault.models.CertificateBundle; +import com.microsoft.azure.keyvault.models.CertificateIssuerItem; +import com.microsoft.azure.keyvault.models.CertificateItem; +import com.microsoft.azure.keyvault.models.CertificateOperation; +import com.microsoft.azure.keyvault.models.CertificatePolicy; +import com.microsoft.azure.keyvault.models.Contacts; +import com.microsoft.azure.keyvault.models.IssuerBundle; +import com.microsoft.azure.keyvault.models.IssuerReference; +import com.microsoft.azure.keyvault.models.KeyBundle; +import com.microsoft.azure.keyvault.models.KeyItem; +import com.microsoft.azure.keyvault.models.KeyOperationResult; +import com.microsoft.azure.keyvault.models.KeyVerifyResult; +import com.microsoft.azure.keyvault.models.SecretBundle; +import com.microsoft.azure.keyvault.models.SecretItem; +import com.microsoft.azure.keyvault.models.SecretProperties; +import com.microsoft.azure.keyvault.models.X509CertificateProperties; +import com.microsoft.azure.keyvault.requests.CreateCertificateRequest; +import com.microsoft.azure.keyvault.requests.CreateKeyRequest; +import com.microsoft.azure.keyvault.requests.SetCertificateIssuerRequest; +import com.microsoft.azure.keyvault.requests.SetSecretRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificateIssuerRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificateOperationRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificatePolicyRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificateRequest; +import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; +import com.microsoft.azure.keyvault.requests.UpdateSecretRequest; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; + + +public class AsyncOperationsTest extends KeyVaultClientIntegrationTestBase { + + @Test + public void keyAsync() throws Exception { + + String vault = getVaultUri(); + String keyname = "mykey"; + + CreateKeyRequest createKeyRequest = new CreateKeyRequest.Builder(vault, keyname, "RSA").build(); + KeyBundle keyBundle = keyVaultClient.createKeyAsync(createKeyRequest, null).get().getBody(); + Assert.assertNotNull(keyBundle); + + UpdateKeyRequest updateKeyRequest = new UpdateKeyRequest.Builder(keyBundle.key().kid()).build(); + keyBundle = keyVaultClient.updateKeyAsync(updateKeyRequest, null).get().getBody(); + Assert.assertNotNull(keyBundle); + + keyBundle = keyVaultClient.getKeyAsync(keyBundle.key().kid(), null).get().getBody(); + Assert.assertNotNull(keyBundle); + + List keyItems = keyVaultClient.listKeysAsync(vault, 2, null).get().getBody(); + Assert.assertNotNull(keyItems); + + List keyVersionItems = keyVaultClient.listKeyVersionsAsync(getVaultUri(), keyname, 2, null).get().getBody(); + Assert.assertNotNull(keyVersionItems); + + BackupKeyResult backupResult = keyVaultClient.backupKeyAsync(vault, keyname, null).get().getBody(); + Assert.assertNotNull(backupResult); + + keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get(); + + KeyBundle restoreResult = keyVaultClient.restoreKeyAsync(vault, backupResult.value(), null).get().getBody(); + Assert.assertNotNull(restoreResult); + + KeyOperationResult encryptResult = keyVaultClient.encryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, new byte[100], null).get().getBody(); + Assert.assertNotNull(encryptResult); + + KeyOperationResult decryptResult = keyVaultClient.decryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, encryptResult.result(), null).get().getBody(); + Assert.assertNotNull(decryptResult); + + KeyOperationResult wrapResult = keyVaultClient.wrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, new byte[100], null).get().getBody(); + Assert.assertNotNull(wrapResult); + + KeyOperationResult unwrapResult = keyVaultClient.unwrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, wrapResult.result(), null).get().getBody(); + Assert.assertNotNull(unwrapResult); + + byte[] plainText = new byte[100]; + new Random(0x1234567L).nextBytes(plainText); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(plainText); + byte[] digest = md.digest(); + KeyOperationResult signResult = keyVaultClient.signAsync(keyBundle.key().kid(), JsonWebKeySignatureAlgorithm.RS256, digest, null).get().getBody(); + Assert.assertNotNull(signResult); + + KeyVerifyResult verifypResult = keyVaultClient.verifyAsync(keyBundle.key().kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signResult.result(), null).get().getBody(); + Assert.assertTrue(verifypResult.value()); + + keyBundle = keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get().getBody(); + Assert.assertNotNull(keyBundle); + } + + @Test + public void secretAsync() throws Exception { + + String vault = getVaultUri(); + String secretname = "mySecret"; + String password = "password"; + + SetSecretRequest setSecretRequest = new SetSecretRequest.Builder(vault, secretname, password).build(); + SecretBundle secretBundle = keyVaultClient.setSecretAsync(setSecretRequest, null).get().getBody(); + Assert.assertNotNull(secretBundle); + + UpdateSecretRequest updateSecretRequest = new UpdateSecretRequest.Builder(secretBundle.id()).build(); + secretBundle = keyVaultClient.updateSecretAsync(updateSecretRequest, null).get().getBody(); + Assert.assertNotNull(secretBundle); + + secretBundle = keyVaultClient.getSecretAsync(secretBundle.id(), null).get().getBody(); + Assert.assertNotNull(secretBundle); + + List secretItems = keyVaultClient.listSecretsAsync(vault, 2, null).get().getBody(); + Assert.assertNotNull(secretItems); + + List secretVersionItems = keyVaultClient.listSecretVersionsAsync(vault, secretname, 2, null).get().getBody(); + Assert.assertNotNull(secretVersionItems); + + secretBundle = keyVaultClient.deleteSecretAsync(vault, secretname, null).get().getBody(); + Assert.assertNotNull(secretBundle); + } + + @Test + public void certificateAsync() throws Exception { + + String vault = getVaultUri(); + String certificateName = "myCertificate"; + + CreateCertificateRequest createCertificateRequest = + new CreateCertificateRequest + .Builder(vault, certificateName) + .withPolicy(new CertificatePolicy() + .withSecretProperties(new SecretProperties().withContentType("application/x-pkcs12")) + .withIssuerReference(new IssuerReference().withName("Self")) + .withX509CertificateProperties(new X509CertificateProperties() + .withSubject("CN=SelfSignedJavaPkcs12") + .withValidityInMonths(12))) + .build(); + CertificateOperation certificateOperation = keyVaultClient.createCertificateAsync(createCertificateRequest, null).get().getBody(); + Assert.assertNotNull(certificateOperation); + + UpdateCertificateOperationRequest updateCertificateOperationRequest = new UpdateCertificateOperationRequest.Builder(vault, certificateName, false).build(); + certificateOperation = keyVaultClient.updateCertificateOperationAsync(updateCertificateOperationRequest, null).get().getBody(); + Assert.assertNotNull(certificateOperation); + + Map tags = new HashMap(); + tags.put("tag1", "foo"); + UpdateCertificateRequest updateCertificateRequest = new UpdateCertificateRequest.Builder(vault, certificateName).withTags(tags).build(); + CertificateBundle certificateBundle = keyVaultClient.updateCertificateAsync(updateCertificateRequest, null).get().getBody(); + Assert.assertNotNull(certificateBundle); + + UpdateCertificatePolicyRequest updateCertificatePolicyRequest = new UpdateCertificatePolicyRequest.Builder(vault, certificateName).build(); + CertificatePolicy certificatePolicy = keyVaultClient.updateCertificatePolicyAsync(updateCertificatePolicyRequest, null).get().getBody(); + Assert.assertNotNull(certificatePolicy); + + certificatePolicy = keyVaultClient.getCertificatePolicyAsync(vault, certificateName, null).get().getBody(); + Assert.assertNotNull(certificatePolicy); + + certificateOperation = keyVaultClient.getCertificateOperationAsync(vault, certificateName, null).get().getBody(); + Assert.assertNotNull(certificateOperation); + + certificateBundle = keyVaultClient.getCertificateAsync(vault, certificateName, null).get().getBody(); + Assert.assertNotNull(certificateBundle); + + String cert = keyVaultClient.getPendingCertificateSigningRequestAsync(vault, certificateName, null).get().getBody(); + Assert.assertTrue(!cert.isEmpty()); + + List certificateItem = keyVaultClient.listCertificatesAsync(vault, null).get().getBody(); + Assert.assertNotNull(certificateItem); + + List certificateVersionItem = keyVaultClient.listCertificateVersionsAsync(vault, certificateName, null).get().getBody(); + Assert.assertNotNull(certificateVersionItem); + + + keyVaultClient.deleteCertificateOperationAsync(vault, certificateName, null).get().getBody(); + keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get().getBody(); + } + + @Test + public void issuerAsync() throws Exception { + + String vault = getVaultUri(); + String issuerName = "myIssuer"; + + SetCertificateIssuerRequest setCertificateIssuerRequest = new SetCertificateIssuerRequest.Builder(vault, issuerName, "Test").build(); + IssuerBundle certificateIssuer = keyVaultClient.setCertificateIssuerAsync(setCertificateIssuerRequest, null).get().getBody(); + Assert.assertNotNull(certificateIssuer); + + UpdateCertificateIssuerRequest updateCertificateIssuerRequest = new UpdateCertificateIssuerRequest.Builder(vault, issuerName, "SslAdmin").build(); + certificateIssuer = keyVaultClient.updateCertificateIssuerAsync(updateCertificateIssuerRequest, null).get().getBody(); + Assert.assertNotNull(certificateIssuer); + + certificateIssuer = keyVaultClient.getCertificateIssuerAsync(vault, issuerName, null).get().getBody(); + Assert.assertNotNull(certificateIssuer); + + List issuers = keyVaultClient.listCertificateIssuersAsync(vault, null).get().getBody(); + Assert.assertNotNull(issuers); + + keyVaultClient.deleteCertificateIssuerAsync(vault, issuerName, null).get().getBody(); + } + + + @Test + public void certificateContactsAsync() throws Exception { + + String vault = getVaultUri(); + + Contacts contacts = keyVaultClient.setCertificateContactsAsync(vault, new Contacts(), null).get().getBody(); + Assert.assertNotNull(contacts); + + contacts = keyVaultClient.getCertificateContactsAsync(vault, null).get().getBody(); + Assert.assertNotNull(contacts); + + keyVaultClient.deleteCertificateContactsAsync(vault, null).get(); + } +} diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java index daa3f644c3ca6..85839d816a2aa 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -20,14 +20,15 @@ import java.io.ByteArrayInputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyStore; +import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -35,8 +36,10 @@ import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; @@ -48,6 +51,7 @@ import javax.crypto.NoSuchPaddingException; import org.apache.commons.codec.binary.Base64; +import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; @@ -55,6 +59,7 @@ import com.microsoft.azure.keyvault.CertificateIdentifier; import com.microsoft.azure.keyvault.SecretIdentifier; import com.microsoft.azure.keyvault.models.AdministratorDetails; +import com.microsoft.azure.keyvault.models.CertificateAttributes; import com.microsoft.azure.keyvault.models.CertificateBundle; import com.microsoft.azure.keyvault.models.Contact; import com.microsoft.azure.keyvault.models.Contacts; @@ -73,814 +78,589 @@ import com.microsoft.azure.keyvault.requests.ImportCertificateRequest; import com.microsoft.azure.keyvault.requests.SetCertificateIssuerRequest; import com.microsoft.azure.keyvault.requests.UpdateCertificateIssuerRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificateOperationRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificatePolicyRequest; +import com.microsoft.azure.keyvault.requests.UpdateCertificateRequest; public class CertificateOperationsTest extends KeyVaultClientIntegrationTestBase { - static final String ALGO_RSA = "RSA"; + static final String ALGO_RSA = "RSA"; - static final String X509 = "X.509"; + static final String X509 = "X.509"; - static final String PKCS12 = "PKCS12"; + static final String PKCS12 = "PKCS12"; - static final String MIME_PKCS12 = "application/x-pkcs12"; + static final String MIME_PKCS12 = "application/x-pkcs12"; - static final String MIME_PEM = "application/x-pem-file"; + static final String MIME_PEM = "application/x-pem-file"; - static final String ISSUER_SELF = "Self"; + static final String ISSUER_SELF = "Self"; - static final String ISSUER_TEST = "Test"; - - static final String ISSUER_UNKNOWN = "Unknown"; - - static final String STATUS_IN_PROGRESS = "inProgress"; + static final String ISSUER_TEST = "Test"; + + static final String ISSUER_UNKNOWN = "Unknown"; + + static final String STATUS_IN_PROGRESS = "inProgress"; - static final String STATUS_COMPLETED = "Completed"; + static final String STATUS_COMPLETED = "Completed"; - static final Base64 _base64 = new Base64(-1, null, true); + static final Base64 _base64 = new Base64(-1, null, true); - static final Pattern _privateKey = Pattern.compile("-{5}BEGIN PRIVATE KEY-{5}(?:\\s|\\r|\\n)+" - + "([a-zA-Z0-9+/=\r\n]+)" + "-{5}END PRIVATE KEY-{5}(?:\\s|\\r|\\n)+"); + static final Pattern _privateKey = Pattern.compile("-{5}BEGIN PRIVATE KEY-{5}(?:\\s|\\r|\\n)+" + + "([a-zA-Z0-9+/=\r\n]+)" + "-{5}END PRIVATE KEY-{5}(?:\\s|\\r|\\n)+"); - static final Pattern _certificate = Pattern.compile("-{5}BEGIN CERTIFICATE-{5}(?:\\s|\\r|\\n)+" - + "([a-zA-Z0-9+/=\r\n]+)" + "-{5}END CERTIFICATE-{5}(?:\\s|\\r|\\n)+"); + static final Pattern _certificate = Pattern.compile("-{5}BEGIN CERTIFICATE-{5}(?:\\s|\\r|\\n)+" + + "([a-zA-Z0-9+/=\r\n]+)" + "-{5}END CERTIFICATE-{5}(?:\\s|\\r|\\n)+"); - private static final int MAX_CERTS = 4; + private static final int MAX_CERTS = 4; private static final int PAGELIST_MAX_CERTS = 3; - /** - * Create a self-signed certificate in PKCS12 format (which includes the - * private key) certificate. - * - * @throws Exception - */ - @Test - public void createSelfSignedCertificatePkcs12() throws Exception { - // Set content type to indicate the certificate is PKCS12 format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PKCS12); - - X509CertificateProperties x509Properties = new X509CertificateProperties(); - String subjectName = "CN=SelfSignedJavaPkcs12"; - x509Properties.withSubject(subjectName); - x509Properties.withValidityInMonths(12); - - // Set issuer to "Self" - IssuerReference issuerReference = new IssuerReference(); - issuerReference.withName(ISSUER_SELF); - - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - certificatePolicy.withIssuerReference(issuerReference); - certificatePolicy.withX509CertificateProperties(x509Properties); - - String vaultUri = getVaultUri(); - String certificateName = "createSelfSignedJavaPkcs12"; - CertificateOperation certificateOperation = keyVaultClient.createCertificate( - new CreateCertificateRequest - .Builder(vaultUri, certificateName) - .withPolicy(certificatePolicy) - .build()).getBody(); - - Assert.assertNotNull(certificateOperation); - Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); - - CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); - Assert.assertNotNull(certificateBundle); - Assert.assertNotNull(certificateBundle.id()); - Assert.assertNotNull(certificateBundle.keyIdentifier()); - Assert.assertNotNull(certificateBundle.secretIdentifier()); - Assert.assertNotNull(certificateBundle.x509Thumbprint()); - - // Load the CER part into X509Certificate object - Assert.assertNotNull(certificateBundle.cer()); - ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); - cerStream.close(); - - Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); - Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); - - // Retrieve the secret backing the certificate - SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - - // Load the secret into a KeyStore - ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value())); - String secretPassword = ""; - KeyStore keyStore = KeyStore.getInstance(PKCS12); - keyStore.load(secretStream, secretPassword.toCharArray()); - secretStream.close(); - - // Validate the certificate in the KeyStore - String defaultAlias = Collections.list(keyStore.aliases()).get(0); - X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias); - Assert.assertNotNull(secretCertificate); - Assert.assertTrue(secretCertificate.getPublicKey().equals(x509Certificate.getPublicKey())); - Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() - .equals(x509Certificate.getSubjectX500Principal().getName())); - Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() - .equals(x509Certificate.getIssuerX500Principal().getName())); - Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); - - // Validate the key in the KeyStore - Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray()); - Assert.assertNotNull(secretKey); - Assert.assertTrue(secretKey instanceof PrivateKey); - PrivateKey secretPrivateKey = (PrivateKey) secretKey; - - // Create a KeyPair with the private key from the KeyStore and public - // key from the certificate to verify they match - KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); - Assert.assertNotNull(keyPair); - verifyRSAKeyPair(keyPair); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - Assert.assertNotNull(deletedCertificateBundle); - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - - /** - * Create a self-signed certificate in PEM format (which includes the - * private key) certificate. - * - * @throws Exception - */ - @Test - public void createSelfSignedCertificatePem() throws Exception { - // Set content type to indicate the certificate is PKCS12 format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PEM); - - X509CertificateProperties x509Properties = new X509CertificateProperties(); - String subjectName = "CN=SelfSignedJavaPem"; - x509Properties.withSubject(subjectName); - x509Properties.withValidityInMonths(12); - - // Set issuer to "Self" - IssuerReference issuerReference = new IssuerReference(); - issuerReference.withName(ISSUER_SELF); - - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - certificatePolicy.withIssuerReference(issuerReference); - certificatePolicy.withX509CertificateProperties(x509Properties); - - String vaultUri = getVaultUri(); - String certificateName = "SelfSignedJavaPem"; - CertificateOperation certificateOperation = keyVaultClient.createCertificate( - new CreateCertificateRequest - .Builder(vaultUri, certificateName) - .withPolicy(certificatePolicy) - .build()).getBody(); - - Assert.assertNotNull(certificateOperation); - Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); - - CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); - Assert.assertNotNull(certificateBundle); - Assert.assertNotNull(certificateBundle.id()); - Assert.assertNotNull(certificateBundle.kid()); - Assert.assertNotNull(certificateBundle.sid()); - Assert.assertNotNull(certificateBundle.x509Thumbprint()); - - // Load the CER part into X509Certificate object - Assert.assertNotNull(certificateBundle.cer()); - ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); - cerStream.close(); - - Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); - Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); - - // Retrieve the secret backing the certificate - SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - String secretValue = secret.value(); - - // Extract private key from PEM - PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue); - Assert.assertNotNull(secretPrivateKey); - - // Extract certificates from PEM - List certificates = extractCertificatesFromPemContents(secretValue); - Assert.assertNotNull(certificates); - Assert.assertTrue(certificates.size() == 1); - - // has the public key corresponding to the private key. - X509Certificate secretCertificate = certificates.get(0); - Assert.assertNotNull(secretCertificate); - Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() - .equals(x509Certificate.getSubjectX500Principal().getName())); - Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() - .equals(x509Certificate.getIssuerX500Principal().getName())); - Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); - - // Create a KeyPair with the private key from the KeyStore and public - // key from the certificate to verify they match - KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); - Assert.assertNotNull(keyPair); - verifyRSAKeyPair(keyPair); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - Assert.assertNotNull(deletedCertificateBundle); - - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - - /** - * Create a test-issuer issued certificate in PKCS12 format (which includes - * the private key) certificate. - * - * @throws Exception - */ - @Test - public void createCertificatePkcs12() throws Exception { - // Construct organization administrator details - AdministratorDetails administratorDetails = new AdministratorDetails(); - administratorDetails.withFirstName("John"); - administratorDetails.withLastName("Doe"); - administratorDetails.withEmailAddress("john.doe@contoso.com"); - administratorDetails.withPhone("1234567890"); - - // Construct organization details - OrganizationDetails organizationDetails = new OrganizationDetails(); - List administratorsDetails = new ArrayList(); - administratorsDetails.add(administratorDetails); - organizationDetails.withAdminDetails(administratorsDetails); - - // Construct certificate issuer credentials - IssuerCredentials credentials = new IssuerCredentials(); - credentials.withAccountId("account1"); - credentials.withPassword("Pa$$w0rd"); - - IssuerBundle certificateIssuer = new IssuerBundle(); - certificateIssuer.withProvider(ISSUER_TEST); - certificateIssuer.withCredentials(credentials); - certificateIssuer.withOrganizationDetails(organizationDetails); - - String certificateIssuerName = "createCertificateJavaPkcs12Issuer01"; - IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( - new SetCertificateIssuerRequest - .Builder(getVaultUri(),certificateIssuerName) - .withIssuer(certificateIssuer) - .build()).getBody(); - - Assert.assertNotNull(createdCertificateIssuer); - Assert.assertNotNull(createdCertificateIssuer.issuerIdentifier()); - Assert.assertNotNull(createdCertificateIssuer.issuerIdentifier().name()); - Assert.assertTrue(createdCertificateIssuer.issuerIdentifier().name().equalsIgnoreCase(certificateIssuerName)); - - // Set content type to indicate the certificate is PKCS12 format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PKCS12); - - X509CertificateProperties x509Properties = new X509CertificateProperties(); - String subjectName = "CN=TestJavaPkcs12"; - x509Properties.withSubject(subjectName); - x509Properties.withValidityInMonths(12); - - // Set issuer reference to the created issuer - IssuerReference issuerReference = new IssuerReference(); - issuerReference.withName(createdCertificateIssuer.issuerIdentifier().name()); - - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - certificatePolicy.withIssuerReference(issuerReference); - certificatePolicy.withX509CertificateProperties(x509Properties); - - String vaultUri = getVaultUri(); - String certificateName = "createTestJavaPkcs12"; - CertificateOperation certificateOperation = keyVaultClient.createCertificate( - new CreateCertificateRequest - .Builder(vaultUri, certificateName) - .withPolicy(certificatePolicy) - .build()).getBody(); - - Assert.assertNotNull(certificateOperation); - Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); - - CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); - Assert.assertNotNull(certificateBundle); - Assert.assertNotNull(certificateBundle.id()); - Assert.assertNotNull(certificateBundle.keyIdentifier()); - Assert.assertNotNull(certificateBundle.secretIdentifier()); - Assert.assertNotNull(certificateBundle.x509Thumbprint()); - Assert.assertNotNull(certificateBundle.policy()); - Assert.assertNotNull(certificateBundle.policy().issuerReference()); - Assert.assertNotNull(certificateBundle.policy().issuerReference().name()); - Assert.assertTrue( - certificateBundle.policy().issuerReference().name().equalsIgnoreCase(certificateIssuerName)); - - // Load the CER part into X509Certificate object - Assert.assertNotNull(certificateBundle.cer()); - ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); - cerStream.close(); - - Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); - Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); - - // Retrieve the secret backing the certificate - SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - - // Load the secret into a KeyStore - ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value())); - String secretPassword = ""; - KeyStore keyStore = KeyStore.getInstance(PKCS12); - keyStore.load(secretStream, secretPassword.toCharArray()); - secretStream.close(); - - // Validate the certificate in the KeyStore - String defaultAlias = Collections.list(keyStore.aliases()).get(0); - X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias); - Assert.assertNotNull(secretCertificate); - Assert.assertTrue(secretCertificate.getPublicKey().equals(x509Certificate.getPublicKey())); - Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() - .equals(x509Certificate.getSubjectX500Principal().getName())); - Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() - .equals(x509Certificate.getIssuerX500Principal().getName())); - Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); - - // Validate the key in the KeyStore - Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray()); - Assert.assertNotNull(secretKey); - Assert.assertTrue(secretKey instanceof PrivateKey); - PrivateKey secretPrivateKey = (PrivateKey) secretKey; - - // Create a KeyPair with the private key from the KeyStore and public - // key from the certificate to verify they match - KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); - Assert.assertNotNull(keyPair); - verifyRSAKeyPair(keyPair); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - Assert.assertNotNull(deletedCertificateBundle); - - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - - /** - * Create a test-issuer certificate in PEM format (which includes the - * private key) certificate. - * - * @throws Exception - */ - @Test - public void createCertificatePem() throws Exception { - // Construct organization administrator details - AdministratorDetails administratorDetails = new AdministratorDetails(); - administratorDetails.withFirstName("John"); - administratorDetails.withLastName("Doe"); - administratorDetails.withEmailAddress("john.doe@contoso.com"); - administratorDetails.withPhone("1234567890"); - - // Construct organization details - OrganizationDetails organizationDetails = new OrganizationDetails(); - List administratorsDetails = new ArrayList(); - administratorsDetails.add(administratorDetails); - organizationDetails.withAdminDetails(administratorsDetails); - - // Construct certificate issuer credentials - IssuerCredentials credentials = new IssuerCredentials(); - credentials.withAccountId("account1"); - credentials.withPassword("Pa$$w0rd"); - - IssuerBundle certificateIssuer = new IssuerBundle(); - certificateIssuer.withProvider(ISSUER_TEST); - certificateIssuer.withCredentials(credentials); - certificateIssuer.withOrganizationDetails(organizationDetails); - - String certificateIssuerName = "createCertificateJavaPemIssuer01"; - IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( - new SetCertificateIssuerRequest - .Builder(getVaultUri(), certificateIssuerName) - .withIssuer(certificateIssuer) - .build()).getBody(); - Assert.assertNotNull(createdCertificateIssuer); - Assert.assertNotNull(createdCertificateIssuer.issuerIdentifier()); - Assert.assertNotNull(createdCertificateIssuer.issuerIdentifier().name()); - Assert.assertTrue(createdCertificateIssuer.issuerIdentifier().name().equalsIgnoreCase(certificateIssuerName)); - - // Set content type to indicate the certificate is PEM format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PEM); - - X509CertificateProperties x509Properties = new X509CertificateProperties(); - String subjectName = "CN=TestJavaPem"; - x509Properties.withSubject(subjectName); - x509Properties.withValidityInMonths(12); - - // Set issuer reference to the created issuer - IssuerReference issuerReference = new IssuerReference(); - issuerReference.withName(createdCertificateIssuer.issuerIdentifier().name()); - - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - certificatePolicy.withIssuerReference(issuerReference); - certificatePolicy.withX509CertificateProperties(x509Properties); - - String vaultUri = getVaultUri(); - String certificateName = "createTestJavaPem"; - CertificateOperation certificateOperation = keyVaultClient.createCertificate( - new CreateCertificateRequest - .Builder(vaultUri, certificateName) - .withPolicy(certificatePolicy) - .build()).getBody(); - - Assert.assertNotNull(certificateOperation); - Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); - - CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); - Assert.assertNotNull(certificateBundle); - Assert.assertNotNull(certificateBundle.id()); - Assert.assertNotNull(certificateBundle.kid()); - Assert.assertNotNull(certificateBundle.sid()); - Assert.assertNotNull(certificateBundle.x509Thumbprint()); - Assert.assertNotNull(certificateBundle.policy()); - Assert.assertNotNull(certificateBundle.policy().issuerReference()); - Assert.assertNotNull(certificateBundle.policy().issuerReference().name()); - Assert.assertTrue( - certificateBundle.policy().issuerReference().name().equalsIgnoreCase(certificateIssuerName)); - - // Load the CER part into X509Certificate object - Assert.assertNotNull(certificateBundle.cer()); - ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); - cerStream.close(); - - Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); - Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); - - // Retrieve the secret backing the certificate - SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - String secretValue = secret.value(); - - // Extract private key from PEM - PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue); - Assert.assertNotNull(secretPrivateKey); - - // Extract certificates from PEM - List certificates = extractCertificatesFromPemContents(secretValue); - Assert.assertNotNull(certificates); - Assert.assertTrue(certificates.size() == 1); - - // has the public key corresponding to the private key. - X509Certificate secretCertificate = certificates.get(0); - Assert.assertNotNull(secretCertificate); - Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() - .equals(x509Certificate.getSubjectX500Principal().getName())); - Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() - .equals(x509Certificate.getIssuerX500Principal().getName())); - Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); - - // Create a KeyPair with the private key from the KeyStore and public - // key from the certificate to verify they match - KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); - Assert.assertNotNull(keyPair); - verifyRSAKeyPair(keyPair); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - Assert.assertNotNull(deletedCertificateBundle); - - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } - catch(KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - - /** - * Create a certificate signing request with key in Key Vault. - * @throws ExecutionException - * @throws InterruptedException - * @throws IOException - * @throws IllegalArgumentException - * @throws KeyVaultErrorException - * - * @throws Exception - */ - @Test - public void createCsr() throws InterruptedException, ExecutionException, KeyVaultErrorException, IllegalArgumentException, IOException { - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PKCS12); - - X509CertificateProperties x509Properties = new X509CertificateProperties(); - String subjectName = "CN=ManualEnrollmentJava"; - x509Properties.withSubject(subjectName); - x509Properties.withValidityInMonths(12); - - // Set issuer to "Unknown" - IssuerReference issuerReference = new IssuerReference(); - issuerReference.withName(ISSUER_UNKNOWN); - - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - certificatePolicy.withIssuerReference(issuerReference); - certificatePolicy.withX509CertificateProperties(x509Properties); - - String vaultUri = getVaultUri(); - String certificateName = "createManualEnrollmentJava"; - CertificateOperation certificateOperation = keyVaultClient.createCertificate( - new CreateCertificateRequest - .Builder(vaultUri, certificateName) - .withPolicy(certificatePolicy) - .build()).getBody(); - - Assert.assertNotNull(certificateOperation); - Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); - Assert.assertNotNull(certificateOperation.csr()); - - String csr = keyVaultClient.getPendingCertificateSigningRequest(vaultUri, certificateName).getBody(); - Assert.assertNotNull(csr); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - Assert.assertNotNull(deletedCertificateBundle); - - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - /** - * Import a PKCS12 format (which includes the private key) certificate. - */ - @Test - public void importCertificatePkcs12() throws Exception { - String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; - String certificatePassword = "123"; - - // Set content type to indicate the certificate is PKCS12 format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PKCS12); - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - - String vaultUri = getVaultUri(); - String certificateName = "importCertPkcs"; - CertificateBundle certificateBundle = keyVaultClient.importCertificate( - new ImportCertificateRequest - .Builder(vaultUri, certificateName, certificateContent) - .withPassword(certificatePassword) - .withPolicy(certificatePolicy) - .build()).getBody(); - - // Validate the certificate bundle created - Assert.assertNotNull(certificateBundle); - Assert.assertNotNull(certificateBundle.id()); - Assert.assertNotNull(certificateBundle.kid()); - Assert.assertNotNull(certificateBundle.sid()); - Assert.assertNotNull(certificateBundle.x509Thumbprint()); - - Assert.assertTrue(toHexString(certificateBundle.x509Thumbprint()).equalsIgnoreCase("7cb8b7539d87ba7215357b9b9049dff2d3fa59ba")); - - // Load the CER part into X509Certificate object - Assert.assertNotNull(certificateBundle.cer()); - ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); - cerStream.close(); - - Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals("CN=KeyVaultTest")); - Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals("CN=Root Agency")); - - // Retrieve the secret backing the certificate - SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - - // Load the secret into a KeyStore - ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value())); - String secretPassword = ""; - KeyStore keyStore = KeyStore.getInstance(PKCS12); - keyStore.load(secretStream, secretPassword.toCharArray()); - secretStream.close(); - - // Validate the certificate in the KeyStore - String defaultAlias = Collections.list(keyStore.aliases()).get(0); - X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias); - Assert.assertNotNull(secretCertificate); - Assert.assertTrue(secretCertificate.getPublicKey().equals(x509Certificate.getPublicKey())); - Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() - .equals(x509Certificate.getSubjectX500Principal().getName())); - Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() - .equals(x509Certificate.getIssuerX500Principal().getName())); - Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); - - // Validate the key in the KeyStore - Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray()); - Assert.assertNotNull(secretKey); - Assert.assertTrue(secretKey instanceof PrivateKey); - PrivateKey secretPrivateKey = (PrivateKey) secretKey; - - // Create a KeyPair with the private key from the KeyStore and public - // key from the certificate to verify they match - KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); - Assert.assertNotNull(keyPair); - verifyRSAKeyPair(keyPair); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - - /** - * Import a PEM format (which includes a encrypted private key) certificate. - * TODO: Server can't handle this yet. - */ - // @Test - public void importCertificatePem() throws Exception { - String certificateContent = "-----BEGIN ENCRYPTED PRIVATE KEY-----\n" - + "MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI+mprWsX8IMICAggA\n" - + "MBQGCCqGSIb3DQMHBAgu4FUBoWBbGgSCBMhjsFyDgeqAVrMRXKaGpdstAHttWxGw\n" - + "JfkthRr8eULwldl2sYZdxwZaHOWjhhwp3LHZ7M5+6augyo1WxIJ456hPlZQ0nlXO\n" - + "y9pFBXEFSIeemd7JdVPjZ3HWVrkXapcKh12hqhzskdXlBermc5uS5NScOFJhnGFT\n" - + "68Va9KHglOmX2T0fUIagWnxQuP2gu3w3PIbbMt8tB0fN5H2xfd6xjKiTlb+3jHP2\n" - + "kZzAcPCzqgNlCK09fOqD9x+fFO2Zn6SqzPt66E8IMZ/7s41mF5IU8H0rIkA9vOZM\n" - + "oM41r0S+N1nhn1MV52aHcqQETV/odKq968dnLRiSIRLfSI9HQWubXu3jWeDHh3GC\n" - + "gaJbafDZWYjN42xIamm5xv3JEycED3Cqk4ibSJgw72uEIGZmhxzo8cXCelOezCBT\n" - + "aj3IkLfUej9p9UhIZJ6DX3kWFh7Ab5T4c23ZzV1WeDtLSANqh1FHFnWMxAcTOgY0\n" - + "0uPGKW03uz3RQdypI8GbrYlT0QiLAaCT6dijFyGNk8W1eAcFJQS4Vtp7PBG+o1qn\n" - + "+xdXVEiQxpZbiFeSMaydfxWAbin4gr98I55gf2VXq9VOFsRY2LxeNzmmEVt1HjuJ\n" - + "rCl4KB/d7VrB+Ev/zjUHDtD22f/Gca7VRET7FaG9Mdj4trtngKFc3B82Q98a3F2w\n" - + "l7ppYQMwdOFUrDRCCDdmatVJwtg/MAXxaIxwGAow+po0dQx2xyqz/8aIPoSg604d\n" - + "+Z5AEmpyLC7369+OZUtJfQ5bCmFbBLne9YvoDAKXuJ07fx+Sq7Hzrbb3uPQo6vgi\n" - + "QrLJhY8KgCFMMWzsfiVPOIGkWIR2KRiyX2HMbsYGRdhRsGl4xco8mmCv4C9WjR9A\n" - + "AT5mVi6U9/zMG1wJMrnVoPQ1E+pi+nuviWZWKZ8uqYOAOEwewHpuTrdmgPe1yoJ/\n" - + "beIYzTOEt9BemnuQge9/zdhH3U5667xWb08hV5dv1Z9ubLKbZx3Yea/J+EbfNW3B\n" - + "OxuacDsaMSSj1wiKKgeSkusrAikCvlsCJumTRAbu/uR6HgmqIlBpB3JTJHoCx90F\n" - + "BsIcwf73aFs/rQQJ6aZRi/fFgHpxWgtEQ9aTKXmhgbfTjjHYGYGkHvDNdzKaXu46\n" - + "6WliF9G0WAeotaGrRESvqVDswaM0F27KjtSdcmtdUQOtbtVVd84VClZqhbyd6tFh\n" - + "lqFsHO9oN+mQQJNhemqiL/Tdo+BQwGxeWjlstd7HlwUsc1sp0OLA8h8QlteBAnNb\n" - + "KpOQYblZbCZX4uZR5KJYDeCuDmWp/Qg7gcKyRLC9I+PrzYockl375RuK60Lws8B+\n" - + "kW49wYHzJFf7DOwuV/2TwkOwP0jcr9nWkjS1uwryuYbp9zPuqddHWggt2rDIlBIG\n" - + "aCU46hS1cGJmzLcIF8TAg8hPQgSikr1AIseyDnWK96OnrTRVK8TbVWOHwvJWr92g\n" - + "ZLwgAve79qgG4LPCOF1HZSeU9sq81FbzPz+BGdVLn5xkoZ1gyjclR78W6jeeTGH3\n" - + "efiw9atBkAiUKaODMXbtHm93JcSQ5sK0r66J7uAQVjLIMu757V0paJNjfF5WoisC\n" - + "3nwuSbg71YHNgvlx/OYWRBRreT/zDgApvnrYqUsUPSQaybMc/9Pbjj76T4AWmjVa\n" - + "JHA=\n" - + "-----END ENCRYPTED PRIVATE KEY-----\n" - + "-----BEGIN CERTIFICATE-----\n" - + "MIIDozCCAougAwIBAgIJAIvNGnmenqgjMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNV\n" - + "BAYTAlVTMQswCQYDVQQIDAJXQTEQMA4GA1UEBwwHUmVkbW9uZDEXMBUGA1UECgwO\n" - + "TWljcm9zb2Z0IENvcnAxDjAMBgNVBAsMBUF6dXJlMREwDwYDVQQDDAhLZXlWYXVs\n" - + "dDAeFw0xNjA0MDEyMzAwMjlaFw0xNjA1MzEyMzAwMjlaMGgxCzAJBgNVBAYTAlVT\n" - + "MQswCQYDVQQIDAJXQTEQMA4GA1UEBwwHUmVkbW9uZDEXMBUGA1UECgwOTWljcm9z\n" - + "b2Z0IENvcnAxDjAMBgNVBAsMBUF6dXJlMREwDwYDVQQDDAhLZXlWYXVsdDCCASIw\n" - + "DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAN1udkhsWIwmua3SFJWxS9AJoKK5\n" - + "o7RAHwsQUWWNkSsPiWrzDYXarfUEs1HBEsAjOJDabK1L0ahw4Manx0NXDOmw8kuD\n" - + "lNMs4yTZNxvECvKpq37Z6Q3D9ts4sVSeFbXtOYr81P+8DOOH3Ibk3sldoJBMXJ5h\n" - + "pw4R72988m9CZ9KjcdaKFk3L1baCehpwkJLZD2XD7MzV9YBKNnd15DPCkVZHul1t\n" - + "bW0E7kf7vUOPIfRuNZeN6QvqsKTA+RoGh3CVu9QV+XG/AsHDoHUwGUlJPvOCm3U5\n" - + "tDrrbXAP+Wa/kE/fGAJkZQLPcbappUI4Swtt9u7+CpyQ96H7BY1yHvmBzBUCAwEA\n" - + "AaNQME4wHQYDVR0OBBYEFJ9DSIY/4ODmWY7oIQkGDD7KlQnAMB8GA1UdIwQYMBaA\n" - + "FJ9DSIY/4ODmWY7oIQkGDD7KlQnAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEL\n" - + "BQADggEBAGV3fTAVWd1tdgcaogBirn1LF8d3H45bdDtjD98933dsOCYlXHKNdB62\n" - + "6Qwg6XF9a+p1vuHI1I8MKBu//q+pLJce+bi2jmge64zlz/iO3sLSOFo/q1EWzhal\n" - + "TRglNkvqWr7OvJXdUznQI3AzjB8tbFB2YerSbmD6FxAAihEq8ZoJ1BsMq5vknpPB\n" - + "iETENaNSjdgPEsiapYNALgY4AVxtSS5GJDZ9zpc5Q6HCPmUozLbQheNZf3+D75cy\n" - + "gB2odtfwhKCuIfuMan51UqjupK0JVJuNV4MXRXH0mFPEBxI4pYolFuV8960jGXqE\n" - + "m/26LtCJLW5QaedtCCKpn9fat5VHgso=\n" - + "-----END CERTIFICATE-----\n"; - - String certificatePassword = "1234"; - - // Set content type to indicate the certificate is PEM format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PEM); - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - - String vaultUri = getVaultUri(); - String certificateName = "importCertPem"; - CertificateBundle certificateBundle = keyVaultClient.importCertificate( - new ImportCertificateRequest - .Builder(vaultUri, certificateName, certificateContent) - .withPassword(certificatePassword) - .withPolicy(certificatePolicy) - .build()).getBody(); - - // Validate the certificate bundle created - Assert.assertNotNull(certificateBundle); - Assert.assertNotNull(certificateBundle.id()); - Assert.assertNotNull(certificateBundle.kid()); - Assert.assertNotNull(certificateBundle.sid()); - Assert.assertNotNull(certificateBundle.x509Thumbprint()); - Assert.assertTrue(toHexString(certificateBundle.x509Thumbprint()).equalsIgnoreCase("d86db6736c335f08ef39aa27ef83836e8eba95b9")); - - // Load the CER part into X509Certificate object - Assert.assertNotNull(certificateBundle.cer()); - ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); - cerStream.close(); - - Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName() - .equals("CN=KeyVault,OU=Azure,O=Microsoft Corp,L=Redmond,ST=WA,C=US")); - Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName() - .equals("CN=KeyVault,OU=Azure,O=Microsoft Corp,L=Redmond,ST=WA,C=US")); - - // Retrieve the secret backing the certificate - SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - - // Load the secret into a KeyStore - ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value())); - String secretPassword = ""; - KeyStore keyStore = KeyStore.getInstance(PKCS12); - keyStore.load(secretStream, secretPassword.toCharArray()); - secretStream.close(); - - // Validate the certificate in the KeyStore - String defaultAlias = Collections.list(keyStore.aliases()).get(0); - X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias); - Assert.assertNotNull(secretCertificate); - Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() - .equals(x509Certificate.getSubjectX500Principal().getName())); - Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() - .equals(x509Certificate.getIssuerX500Principal().getName())); - Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); - - // Validate the key in the KeyStore - Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray()); - Assert.assertNotNull(secretKey); - Assert.assertTrue(secretKey instanceof PrivateKey); - PrivateKey secretPrivateKey = (PrivateKey) secretKey; - - // Create a KeyPair with the private key from the KeyStore and public - // key from the certificate to verify they match - KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); - Assert.assertNotNull(keyPair); - verifyRSAKeyPair(keyPair); - - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); - Assert.assertNotNull(deletedCertificateBundle); - - try { - keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); - } - } - - /** - * List certificates in a vault. - */ - @Test - public void listCertificates() throws Exception { - String certificateName = "listCertificate"; - String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; - String certificatePassword = "123"; - - // Set content type to indicate the certificate is PKCS12 format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PKCS12); - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - - HashSet certificates = new HashSet(); - for (int i = 0; i < MAX_CERTS; ++i) { - int failureCount = 0; - for (;;) { - try { - CertificateBundle certificateBundle = keyVaultClient.importCertificate( - new ImportCertificateRequest - .Builder(getVaultUri(), certificateName + i, certificateContent) - .withPassword(certificatePassword) - .withPolicy(certificatePolicy) - .build()).getBody(); - CertificateIdentifier id = certificateBundle.certificateIdentifier(); - certificates.add(id.baseIdentifier()); - break; + private static final Map sTags = new HashMap(); + + /** + * Create a self-signed certificate in PKCS12 format (which includes the + * private key) certificate. + * + * @throws Exception + */ + @Test + public void createSelfSignedCertificatePkcs12() throws Exception { + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties() + .withContentType(MIME_PKCS12); + + String subjectName = "CN=SelfSignedJavaPkcs12"; + X509CertificateProperties x509Properties = new X509CertificateProperties() + .withSubject(subjectName) + .withValidityInMonths(12); + + // Set issuer to "Self" + IssuerReference issuerReference = new IssuerReference() + .withName(ISSUER_SELF); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerReference(issuerReference) + .withX509CertificateProperties(x509Properties); + + CertificateAttributes attribute = (CertificateAttributes) new CertificateAttributes() + .withEnabled(false) + .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) + .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); + + String vaultUri = getVaultUri(); + String certificateName = "createSelfSignedJavaPkcs12"; + + CreateCertificateRequest createCertificateRequest = + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .withAttributes(attribute) + .withTags(sTags) + .build(); + + CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest).getBody(); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + + CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); + validateCertificateBundle(certificateBundle, certificatePolicy); + compareAttributes(attribute, createCertificateRequest.certificateAttributes()); + + // Load the CER part into X509Certificate object + X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle); + + Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); + Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); + + // Retrieve the secret backing the certificate + SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + + // Load the secret into a KeyStore + String secretPassword = ""; + KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); + + // Validate the certificate and key in the KeyStore + validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + Assert.assertNotNull(deletedCertificateBundle); + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); + } + } + + /** + * Create a self-signed certificate in PEM format (which includes the + * private key) certificate. + * + * @throws Exception + */ + @Test + public void createSelfSignedCertificatePem() throws Exception { + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties() + .withContentType(MIME_PEM); + + String subjectName = "CN=SelfSignedJavaPem"; + X509CertificateProperties x509Properties = new X509CertificateProperties() + .withSubject(subjectName) + .withValidityInMonths(12); + + // Set issuer to "Self" + IssuerReference issuerReference = new IssuerReference() + .withName(ISSUER_SELF); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerReference(issuerReference) + .withX509CertificateProperties(x509Properties); + + String vaultUri = getVaultUri(); + String certificateName = "SelfSignedJavaPem"; + CertificateOperation certificateOperation = keyVaultClient.createCertificate( + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .build()).getBody(); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + + CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); + validateCertificateBundle(certificateBundle, certificatePolicy); + + validatePem(certificateBundle, subjectName); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + Assert.assertNotNull(deletedCertificateBundle); + + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); + } + } + + /** + * Create a test-issuer issued certificate in PKCS12 format (which includes + * the private key) certificate. + * + * @throws Exception + */ + @Test + public void createCertificatePkcs12() throws Exception { + // Construct organization administrator details + AdministratorDetails administratorDetails = new AdministratorDetails() + .withFirstName("John") + .withLastName("Doe") + .withEmailAddress("john.doe@contoso.com") + .withPhone("1234567890"); + + // Construct organization details + List administratorsDetails = new ArrayList(); + administratorsDetails.add(administratorDetails); + OrganizationDetails organizationDetails = new OrganizationDetails() + .withAdminDetails(administratorsDetails); + + // Construct certificate issuer credentials + IssuerCredentials credentials = new IssuerCredentials() + .withAccountId("account1") + .withPassword("Pa$$w0rd"); + + String certificateIssuerName = "createCertificateJavaPkcs12Issuer01"; + IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( + new SetCertificateIssuerRequest + .Builder(getVaultUri(),certificateIssuerName, ISSUER_TEST) + .withCredentials(credentials) + .withOrganizationDetails(organizationDetails) + .build()).getBody(); + + validateCertificateIssuer(createdCertificateIssuer, certificateIssuerName); + + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties() + .withContentType(MIME_PKCS12); + + String subjectName = "CN=TestJavaPkcs12"; + X509CertificateProperties x509Properties = new X509CertificateProperties() + .withSubject(subjectName) + .withValidityInMonths(12); + + // Set issuer reference to the created issuer + IssuerReference issuerReference = new IssuerReference(); + issuerReference.withName(createdCertificateIssuer.issuerIdentifier().name()); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerReference(issuerReference) + .withX509CertificateProperties(x509Properties); + + String vaultUri = getVaultUri(); + String certificateName = "createTestJavaPkcs12"; + CertificateOperation certificateOperation = keyVaultClient.createCertificate( + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .build()).getBody(); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + + CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); + validateCertificateBundle(certificateBundle, certificatePolicy); + + // Load the CER part into X509Certificate object + X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle); + + Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); + Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); + + // Retrieve the secret backing the certificate + SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + + // Load the secret into a KeyStore + String secretPassword = ""; + KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); + + // Validate the certificate and key in the KeyStore + validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + Assert.assertNotNull(deletedCertificateBundle); + + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); + } + } + + /** + * Create a test-issuer certificate in PEM format (which includes the + * private key) certificate. + * + * @throws Exception + */ + @Test + public void createCertificatePem() throws Exception { + // Construct organization administrator details + AdministratorDetails administratorDetails = new AdministratorDetails() + .withFirstName("John") + .withLastName("Doe") + .withEmailAddress("john.doe@contoso.com") + .withPhone("1234567890"); + + // Construct organization details + OrganizationDetails organizationDetails = new OrganizationDetails(); + List administratorsDetails = new ArrayList(); + administratorsDetails.add(administratorDetails); + organizationDetails.withAdminDetails(administratorsDetails); + + // Construct certificate issuer credentials + IssuerCredentials credentials = new IssuerCredentials() + .withAccountId("account1") + .withPassword("Pa$$w0rd"); + + String certificateIssuerName = "createCertificateJavaPemIssuer01"; + IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( + new SetCertificateIssuerRequest + .Builder(getVaultUri(), certificateIssuerName, ISSUER_TEST) + .withCredentials(credentials) + .withOrganizationDetails(organizationDetails) + .build()).getBody(); + validateCertificateIssuer(createdCertificateIssuer, certificateIssuerName); + + // Set content type to indicate the certificate is PEM format. + SecretProperties secretProperties = new SecretProperties(); + secretProperties.withContentType(MIME_PEM); + + X509CertificateProperties x509Properties = new X509CertificateProperties(); + String subjectName = "CN=TestJavaPem"; + x509Properties.withSubject(subjectName); + x509Properties.withValidityInMonths(12); + + // Set issuer reference to the created issuer + IssuerReference issuerReference = new IssuerReference(); + issuerReference.withName(createdCertificateIssuer.issuerIdentifier().name()); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerReference(issuerReference) + .withX509CertificateProperties(x509Properties); + + String vaultUri = getVaultUri(); + String certificateName = "createTestJavaPem"; + CertificateOperation certificateOperation = keyVaultClient.createCertificate( + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .build()).getBody(); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + + CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); + validateCertificateBundle(certificateBundle, certificatePolicy); + + validatePem(certificateBundle, subjectName); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + Assert.assertNotNull(deletedCertificateBundle); + + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } + catch(KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); + } + } + + /** + * Create a certificate signing request with key in Key Vault. + * @throws ExecutionException + * @throws InterruptedException + * @throws IOException + * @throws IllegalArgumentException + * @throws KeyVaultErrorException + * + * @throws Exception + */ + @Test + public void createCsr() throws InterruptedException, ExecutionException, KeyVaultErrorException, IllegalArgumentException, IOException { + SecretProperties secretProperties = new SecretProperties(); + secretProperties.withContentType(MIME_PKCS12); + + X509CertificateProperties x509Properties = new X509CertificateProperties(); + String subjectName = "CN=ManualEnrollmentJava"; + x509Properties.withSubject(subjectName); + x509Properties.withValidityInMonths(12); + + // Set issuer to "Unknown" + IssuerReference issuerReference = new IssuerReference(); + issuerReference.withName(ISSUER_UNKNOWN); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerReference(issuerReference) + .withX509CertificateProperties(x509Properties); + + String vaultUri = getVaultUri(); + String certificateName = "createManualEnrollmentJava"; + CertificateOperation certificateOperation = keyVaultClient.createCertificate( + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .build()).getBody(); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + Assert.assertNotNull(certificateOperation.csr()); + + String csr = keyVaultClient.getPendingCertificateSigningRequest(vaultUri, certificateName).getBody(); + Assert.assertNotNull(csr); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + Assert.assertNotNull(deletedCertificateBundle); + + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); + } + } + + /** + * Cancel the certificate create asynchronously + * @throws IOException + * @throws IllegalArgumentException + * @throws KeyVaultErrorException + * + */ + @Test + public void certificateAsyncRequestCancellation() throws KeyVaultErrorException, IllegalArgumentException, IOException { + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties() + .withContentType(MIME_PKCS12); + + String subjectName = "CN=SelfSignedJavaPkcs12"; + X509CertificateProperties x509Properties = new X509CertificateProperties() + .withSubject(subjectName) + .withValidityInMonths(12); + + // Set issuer to "Self" + IssuerReference issuerReference = new IssuerReference() + .withName(ISSUER_SELF); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerReference(issuerReference) + .withX509CertificateProperties(x509Properties); + + String vaultUri = getVaultUri(); + String certificateName = "cancellationRequestedCertJava"; + keyVaultClient.createCertificate( + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .build()).getBody(); + + CertificateOperation cancelledCertificateOperation = keyVaultClient.updateCertificateOperation( + new UpdateCertificateOperationRequest + .Builder(vaultUri, certificateName, true) + .build()).getBody(); + + Assert.assertNotNull(cancelledCertificateOperation); + Assert.assertTrue(cancelledCertificateOperation.cancellationRequested()); + + keyVaultClient.deleteCertificateOperation(getVaultUri(), certificateName).getBody(); + keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + } + + /** + * Import a PKCS12 format (which includes the private key) certificate. + */ + @Test + public void importCertificatePkcs12() throws Exception { + String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; + String certificatePassword = "123"; + + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12); + CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties); + CertificateAttributes attribute = (CertificateAttributes) new CertificateAttributes().withEnabled(true); + + String vaultUri = getVaultUri(); + String certificateName = "importCertPkcs"; + CertificateBundle certificateBundle = keyVaultClient.importCertificate( + new ImportCertificateRequest + .Builder(vaultUri, certificateName, certificateContent) + .withPassword(certificatePassword) + .withPolicy(certificatePolicy) + .withAttributes(attribute) + .withTags(sTags) + .build()).getBody(); + + // Validate the certificate bundle created + validateCertificateBundle(certificateBundle, certificatePolicy); + Assert.assertTrue(toHexString(certificateBundle.x509Thumbprint()).equalsIgnoreCase("7cb8b7539d87ba7215357b9b9049dff2d3fa59ba")); + Assert.assertEquals(attribute.enabled(), certificateBundle.attributes().enabled()); + + // Load the CER part into X509Certificate object + X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle); + + Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals("CN=KeyVaultTest")); + Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals("CN=Root Agency")); + + // Retrieve the secret backing the certificate + SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + + // Load the secret into a KeyStore + String secretPassword = ""; + KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); + + // Validate the certificate and key in the KeyStore + validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateNotFound", e.getBody().error().code()); + } + } + + /** + * Import a PKCS12 format (which includes the private key) certificate. + */ + @Test + public void certificateUpdate() throws Exception { + String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; + String certificatePassword = "123"; + + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12); + CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties); + + String vaultUri = getVaultUri(); + String certificateName = "updateCertJava"; + keyVaultClient.importCertificate( + new ImportCertificateRequest + .Builder(vaultUri, certificateName, certificateContent) + .withPassword(certificatePassword) + .withPolicy(certificatePolicy) + .build()).getBody(); + + + CertificateAttributes attribute = (CertificateAttributes) new CertificateAttributes() + .withEnabled(false) + .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) + .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); + CertificateBundle updatedCertBundle = keyVaultClient.updateCertificate( + new UpdateCertificateRequest + .Builder(vaultUri, certificateName) + .withAttributes((CertificateAttributes) attribute.withEnabled(false)) + .withTags(sTags) + .build()).getBody(); + Assert.assertEquals(attribute.enabled(), updatedCertBundle.attributes().enabled()); + Assert.assertEquals(sTags.toString(), updatedCertBundle.tags().toString()); + + CertificatePolicy certificatePolicyUpdate = certificatePolicy.withIssuerReference(new IssuerReference().withName(ISSUER_SELF)); + CertificatePolicy updatedCertificatePolicy = keyVaultClient.updateCertificatePolicy( + new UpdateCertificatePolicyRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicyUpdate) + .build()).getBody(); + Assert.assertEquals(certificatePolicyUpdate.issuerReference().name(), updatedCertificatePolicy.issuerReference().name()); + + CertificatePolicy policy = keyVaultClient.getCertificatePolicy(vaultUri, certificateName).getBody(); + Assert.assertEquals(certificatePolicyUpdate.issuerReference().name(), policy.issuerReference().name()); + + keyVaultClient.deleteCertificate(getVaultUri(), certificateName); + } + + /** + * List certificates in a vault. + */ + @Test + public void listCertificates() throws Exception { + String certificateName = "listCertificate"; + String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; + String certificatePassword = "123"; + + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties(); + secretProperties.withContentType(MIME_PKCS12); + CertificatePolicy certificatePolicy = new CertificatePolicy(); + certificatePolicy.withSecretProperties(secretProperties); + + HashSet certificates = new HashSet(); + for (int i = 0; i < MAX_CERTS; ++i) { + int failureCount = 0; + for (;;) { + try { + CertificateBundle certificateBundle = keyVaultClient.importCertificate( + new ImportCertificateRequest + .Builder(getVaultUri(), certificateName + i, certificateContent) + .withPassword(certificatePassword) + .withPolicy(certificatePolicy) + .build()).getBody(); + CertificateIdentifier id = certificateBundle.certificateIdentifier(); + certificates.add(id.baseIdentifier()); + break; } catch (KeyVaultErrorException e) { ++failureCount; if (e.getBody().error().code().equals("Throttled")) { @@ -890,13 +670,13 @@ public void listCertificates() throws Exception { } throw e; } - } - } + } + } - PagedList listResult = keyVaultClient.getCertificates(getVaultUri(), PAGELIST_MAX_CERTS).getBody(); - Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().getItems().size()); + PagedList listResult = keyVaultClient.listCertificates(getVaultUri(), PAGELIST_MAX_CERTS).getBody(); + Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().getItems().size()); - HashSet toDelete = new HashSet(); + HashSet toDelete = new HashSet(); for (CertificateItem item : listResult) { CertificateIdentifier id = new CertificateIdentifier(item.id()); @@ -904,42 +684,42 @@ public void listCertificates() throws Exception { certificates.remove(item.id()); } - Assert.assertEquals(0, certificates.size()); - - for (String toDeleteCertificateName : toDelete) { - keyVaultClient.deleteCertificate(getVaultUri(), toDeleteCertificateName); - } - } - - /** - * List versions of a certificate in a vault. - */ - @Test - public void listCertificateVersions() throws Exception { - String certificateName = "listCertificateVersions"; - String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; - String certificatePassword = "123"; - - // Set content type to indicate the certificate is PKCS12 format. - SecretProperties secretProperties = new SecretProperties(); - secretProperties.withContentType(MIME_PKCS12); - CertificatePolicy certificatePolicy = new CertificatePolicy(); - certificatePolicy.withSecretProperties(secretProperties); - - HashSet certificates = new HashSet(); - for (int i = 0; i < MAX_CERTS; ++i) { - int failureCount = 0; - for (;;) { - try { - CertificateBundle certificateBundle = keyVaultClient.importCertificate( - new ImportCertificateRequest - .Builder(getVaultUri(), certificateName, certificateContent) - .withPassword(certificatePassword) - .withPolicy(certificatePolicy) - .build()).getBody(); - CertificateIdentifier id = certificateBundle.certificateIdentifier(); - certificates.add(id.identifier()); - break; + Assert.assertEquals(0, certificates.size()); + + for (String toDeleteCertificateName : toDelete) { + keyVaultClient.deleteCertificate(getVaultUri(), toDeleteCertificateName); + } + } + + /** + * List versions of a certificate in a vault. + */ + @Test + public void listCertificateVersions() throws Exception { + String certificateName = "listCertificateVersions"; + String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO//J/d4nsgHp6RTuCu4+Jm9k0YTw2Xg75b2cWKrxGnDUgyIlvNPaZTB5QbMid4x44/lE0LLi9kcPQhRgrK07OnnrMgZvVGjt1CLGhKUv7KFc3xV1r1rwKkosxnoG99oCoTQtregcX5rIMjHgkc1IdflGJkZzaWMkYVFOJ4Weynz008i4ddkske5vabZs37Lb8iggUYNBYZyGzalruBgnQyK4fz38Fae4nWYjyildVfgyo/fCePR2ovOfphx9OQJi+M9BoFmPrAg+8ARDZ+R+5yzYuEc9ZoVX7nkp7LTGB3DANBgkrBgEEAYI3EQIxADATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGEAOAAwAGQAZgBmADgANgAtAGUAOQA2AGUALQA0ADIAMgA0AC0AYQBhADEAMQAtAGIAZAAxADkANABkADUAYQA2AGIANwA3MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAHQAcgBvAG4AZwAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIwggLPBgkqhkiG9w0BBwagggLAMIICvAIBADCCArUGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECNX+VL2MxzzWAgIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ"; + String certificatePassword = "123"; + + // Set content type to indicate the certificate is PKCS12 format. + SecretProperties secretProperties = new SecretProperties(); + secretProperties.withContentType(MIME_PKCS12); + CertificatePolicy certificatePolicy = new CertificatePolicy(); + certificatePolicy.withSecretProperties(secretProperties); + + HashSet certificates = new HashSet(); + for (int i = 0; i < MAX_CERTS; ++i) { + int failureCount = 0; + for (;;) { + try { + CertificateBundle certificateBundle = keyVaultClient.importCertificate( + new ImportCertificateRequest + .Builder(getVaultUri(), certificateName, certificateContent) + .withPassword(certificatePassword) + .withPolicy(certificatePolicy) + .build()).getBody(); + CertificateIdentifier id = certificateBundle.certificateIdentifier(); + certificates.add(id.identifier()); + break; } catch (KeyVaultErrorException e) { ++failureCount; if (e.getBody().error().code().equals("Throttled")) { @@ -949,320 +729,399 @@ public void listCertificateVersions() throws Exception { } throw e; } - } - } + } + } - PagedList listResult = keyVaultClient.getCertificateVersions(getVaultUri(), certificateName, PAGELIST_MAX_CERTS).getBody(); + PagedList listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName, PAGELIST_MAX_CERTS).getBody(); Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.getCertificateVersions(getVaultUri(), certificateName).getBody(); - for (;;) { - for (CertificateItem item : listResult) { - certificates.remove(item.id()); + listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName).getBody(); + + for (CertificateItem item : listResult) { + certificates.remove(item.id()); + } + + Assert.assertEquals(0, certificates.size()); + + keyVaultClient.deleteCertificate(getVaultUri(), certificateName); + } + + /** + * CRUD for Certificate issuers + */ + @Test + public void issuerCrudOperations() throws Exception { + // Construct organization administrator details + AdministratorDetails administratorDetails = new AdministratorDetails() + .withFirstName("John") + .withLastName("Doe") + .withEmailAddress("john.doe@contoso.com") + .withPhone("1234567890"); + + // Construct organization details + OrganizationDetails organizationDetails = new OrganizationDetails(); + List administratorsDetails = new ArrayList(); + administratorsDetails.add(administratorDetails); + organizationDetails.withAdminDetails(administratorsDetails); + + // Construct certificate issuer credentials + IssuerCredentials credentials = new IssuerCredentials() + .withAccountId("account1") + .withPassword("Pa$$w0rd"); + + IssuerBundle certificateIssuer = new IssuerBundle() + .withProvider(ISSUER_TEST) + .withCredentials(credentials) + .withOrganizationDetails(organizationDetails); + + IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( + new SetCertificateIssuerRequest + .Builder(getVaultUri(), "issuer1", certificateIssuer.provider()) + .withCredentials(certificateIssuer.credentials()) + .withOrganizationDetails(certificateIssuer.organizationDetails()) + .build()).getBody(); + + validateCertificateIssuer(certificateIssuer, createdCertificateIssuer); + + String certificateIssuerName = createdCertificateIssuer.issuerIdentifier().name(); + IssuerBundle retrievedCertificateIssuer = keyVaultClient.getCertificateIssuer(getVaultUri(), + certificateIssuerName).getBody(); + + validateCertificateIssuer(certificateIssuer, retrievedCertificateIssuer); + + IssuerCredentials updatedCredentials = new IssuerCredentials() + .withAccountId("account2") + .withPassword("Secur!Ty"); + + retrievedCertificateIssuer.withCredentials(updatedCredentials); + IssuerBundle updatedCertificateIssuer = keyVaultClient.updateCertificateIssuer( + new UpdateCertificateIssuerRequest + .Builder(getVaultUri(), certificateIssuerName, ISSUER_TEST) + .withCredentials(updatedCredentials) + .withOrganizationDetails(retrievedCertificateIssuer.organizationDetails()) + .withAttributes(retrievedCertificateIssuer.attributes()) + .build()).getBody(); + + validateCertificateIssuer(retrievedCertificateIssuer, updatedCertificateIssuer); + + Assert.assertNotNull(updatedCertificateIssuer.organizationDetails()); + + IssuerBundle deletedCertificateIssuer = keyVaultClient.deleteCertificateIssuer(getVaultUri(), certificateIssuerName).getBody(); + + validateCertificateIssuer(updatedCertificateIssuer, deletedCertificateIssuer); + + try { + keyVaultClient.getCertificateIssuer(getVaultUri(), certificateIssuerName); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("CertificateIssuerNotFound", e.getBody().error().code()); + } + } + + /** + * CRUD for Certificate contacts + * @throws Exception + */ + @Test + public void contactsCrudOperations() throws Exception { + // Create + Contact contact1 = new Contact(); + contact1.withName("James"); + contact1.withEmailAddress("james@contoso.com"); + contact1.withPhone("7777777777"); + + Contact contact2 = new Contact(); + contact2.withName("Ethan"); + contact2.withEmailAddress("ethan@contoso.com"); + contact2.withPhone("8888888888"); + + List contacts = new ArrayList(); + contacts.add(contact1); + contacts.add(contact2); + + Contacts certificateContacts = new Contacts(); + certificateContacts.withContactList(contacts); + Contacts createdCertificateContacts = keyVaultClient.setCertificateContacts(getVaultUri(), certificateContacts).getBody(); + Assert.assertNotNull(createdCertificateContacts); + Assert.assertNotNull(createdCertificateContacts.contactList()); + Assert.assertTrue(createdCertificateContacts.contactList().size() == 2); + Contact[] createContacts = createdCertificateContacts.contactList().toArray(new Contact[createdCertificateContacts.contactList().size()]); + Assert.assertTrue(createContacts[0].name().equalsIgnoreCase("James")); + Assert.assertTrue(createContacts[0].emailAddress().equalsIgnoreCase("james@contoso.com")); + Assert.assertTrue(createContacts[0].phone().equalsIgnoreCase("7777777777")); + Assert.assertTrue(createContacts[1].name().equalsIgnoreCase("Ethan")); + Assert.assertTrue(createContacts[1].emailAddress().equalsIgnoreCase("ethan@contoso.com")); + Assert.assertTrue(createContacts[1].phone().equalsIgnoreCase("8888888888")); + + // Get + Contacts retrievedCertificateContacts = keyVaultClient.getCertificateContacts(getVaultUri()).getBody(); + Assert.assertNotNull(retrievedCertificateContacts); + Assert.assertNotNull(retrievedCertificateContacts.contactList()); + Assert.assertTrue(retrievedCertificateContacts.contactList().size() == 2); + + // Delete + Contacts deletedCertificateContacts = keyVaultClient.deleteCertificateContacts(getVaultUri()).getBody(); + Assert.assertNotNull(deletedCertificateContacts); + Assert.assertNotNull(deletedCertificateContacts.contactList()); + Assert.assertTrue(deletedCertificateContacts.contactList().size() == 2); + + // Get after delete + try { + keyVaultClient.getCertificateContacts(getVaultUri()).getBody(); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.getBody().error()); + Assert.assertEquals("ContactsNotFound", e.getBody().error().code()); + } + } + + /** + * Polls on a certificate operation for completion. + * + * @throws Exception + */ + private static CertificateBundle pollOnCertificateOperation(CertificateOperation certificateOperation) + throws Exception { + + // Wait for enrollment to complete. We will wait for 200 seconds + int pendingPollCount = 0; + while (pendingPollCount < 21) { + String certificateName = certificateOperation.certificateOperationIdentifier().name(); + CertificateOperation pendingCertificateOperation = keyVaultClient + .getCertificateOperation(getVaultUri(), certificateName).getBody(); + if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)) { + Thread.sleep(10000); + pendingPollCount += 1; + continue; } - String nextLink = listResult.nextPageLink(); - if (nextLink == null) { + + if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_COMPLETED)) { + return keyVaultClient.getCertificate(pendingCertificateOperation.target()).getBody(); + } + + throw new Exception(String.format( + "Polling on pending certificate returned an unexpected result. Error code = {1}, Error message = {2}", + pendingCertificateOperation.error().code(), + pendingCertificateOperation.error().message())); + } + + throw new Exception("Pending certificate processing delayed"); + } + + /** + * Extracts private key from PEM contents + * + * @throws InvalidKeySpecException + * @throws NoSuchAlgorithmException + */ + private static PrivateKey extractPrivateKeyFromPemContents(String pemContents) + throws InvalidKeySpecException, NoSuchAlgorithmException { + Matcher matcher = _privateKey.matcher(pemContents); + if (!matcher.find()) { + throw new IllegalArgumentException("No private key found in PEM contents."); + } + + byte[] privateKeyBytes = _base64.decode(matcher.group(1)); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); + KeyFactory keyFactory = KeyFactory.getInstance(ALGO_RSA); + PrivateKey privateKey = keyFactory.generatePrivate(keySpec); + return privateKey; + } + + /** + * Extracts certificates from PEM contents + * + * @throws CertificateException + * @throws IOException + */ + private static List extractCertificatesFromPemContents(String pemContents) + throws CertificateException, IOException { + Matcher matcher = _certificate.matcher(pemContents); + if (!matcher.find()) { + throw new IllegalArgumentException("No certificate found in PEM contents."); + } + + List result = new ArrayList(); + int offset = 0; + while (true) { + if (!matcher.find(offset)) { break; } - keyVaultClient.getCertificateVersionsNext(nextLink).getBody(); + byte[] certBytes = _base64.decode(matcher.group(1)); + ByteArrayInputStream certStream = new ByteArrayInputStream(certBytes); + CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); + X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certStream); + certStream.close(); + + result.add(x509Certificate); + offset = matcher.end(); } - Assert.assertEquals(0, certificates.size()); + return result; + } + + /** + * Verify a RSA key pair with a simple encrypt/decrypt test. + * + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + */ + private static void verifyRSAKeyPair(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchPaddingException, + InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + // Validate algorithm is RSA + Assert.assertTrue(keyPair.getPublic().getAlgorithm().equals(ALGO_RSA)); + Assert.assertTrue(keyPair.getPrivate().getAlgorithm().equals(ALGO_RSA)); + + // Generate an array of 10 random bytes + byte[] plainData = new byte[10]; + Random random = new Random(); + random.nextBytes(plainData); + + // Encrypt using the public key + Cipher encryptCipher = Cipher.getInstance(ALGO_RSA); + encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); + byte[] encryptedData = encryptCipher.doFinal(plainData); + + // Decrypt using the private key + Cipher decryptCipher = Cipher.getInstance(ALGO_RSA); + decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); + byte[] decryptedData = decryptCipher.doFinal(encryptedData); + + // Validate plainData is equal to decryptedData + Assert.assertArrayEquals(plainData, decryptedData); + } + + private String toHexString(byte[] x5t) { + + if(x5t == null) + return ""; + + StringBuilder hexString = new StringBuilder(); + for (int i = 0; i < x5t.length; i++) { + String hex = Integer.toHexString(0xFF & x5t[i]); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } - keyVaultClient.deleteCertificate(getVaultUri(), certificateName); - } - - /** - * CRUD for Certificate issuers - */ - @Test - public void issuerCrudOperations() throws Exception { - // Construct organization administrator details - AdministratorDetails administratorDetails = new AdministratorDetails(); - administratorDetails.withFirstName("John"); - administratorDetails.withLastName("Doe"); - administratorDetails.withEmailAddress("john.doe@contoso.com"); - administratorDetails.withPhone("1234567890"); - - // Construct organization details - OrganizationDetails organizationDetails = new OrganizationDetails(); - List administratorsDetails = new ArrayList(); - administratorsDetails.add(administratorDetails); - organizationDetails.withAdminDetails(administratorsDetails); - - // Construct certificate issuer credentials - IssuerCredentials credentials = new IssuerCredentials(); - credentials.withAccountId("account1"); - credentials.withPassword("Pa$$w0rd"); - - IssuerBundle certificateIssuer = new IssuerBundle(); - certificateIssuer.withProvider(ISSUER_TEST); - certificateIssuer.withCredentials(credentials); - certificateIssuer.withOrganizationDetails(organizationDetails); - - IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( - new SetCertificateIssuerRequest - .Builder(getVaultUri(), "issuer1") - .withIssuer(certificateIssuer) - .build()).getBody(); - - Assert.assertNotNull(createdCertificateIssuer); - Assert.assertNotNull(createdCertificateIssuer.provider()); - Assert.assertTrue(createdCertificateIssuer.provider().equals("Test")); - - Assert.assertNotNull(createdCertificateIssuer.credentials()); - Assert.assertNotNull(createdCertificateIssuer.credentials().accountId()); - Assert.assertTrue(createdCertificateIssuer.credentials().accountId().equals("account1")); - Assert.assertNull(createdCertificateIssuer.credentials().password()); - - Assert.assertNotNull(createdCertificateIssuer.organizationDetails()); - - String certificateIssuerName = createdCertificateIssuer.issuerIdentifier().name(); - IssuerBundle retrievedCertificateIssuer = keyVaultClient.getCertificateIssuer(getVaultUri(), - certificateIssuerName).getBody(); - - Assert.assertNotNull(retrievedCertificateIssuer); - Assert.assertNotNull(retrievedCertificateIssuer.provider()); - Assert.assertTrue(retrievedCertificateIssuer.provider().equals(ISSUER_TEST)); - - Assert.assertNotNull(retrievedCertificateIssuer.credentials()); - Assert.assertNotNull(retrievedCertificateIssuer.credentials().accountId()); - Assert.assertTrue(retrievedCertificateIssuer.credentials().accountId().equals("account1")); - Assert.assertNull(retrievedCertificateIssuer.credentials().password()); - - Assert.assertNotNull(retrievedCertificateIssuer.organizationDetails()); - - IssuerCredentials updatedCredentials = new IssuerCredentials(); - updatedCredentials.withAccountId("account2"); - updatedCredentials.withPassword("Secur!Ty"); - retrievedCertificateIssuer.withCredentials(updatedCredentials); - IssuerBundle updatedCertificateIssuer = keyVaultClient.updateCertificateIssuer( - new UpdateCertificateIssuerRequest - .Builder(getVaultUri(), certificateIssuerName) - .withIssuer(retrievedCertificateIssuer) - .build()).getBody(); - - Assert.assertNotNull(updatedCertificateIssuer); - Assert.assertNotNull(updatedCertificateIssuer.provider()); - Assert.assertTrue(updatedCertificateIssuer.provider().equals(ISSUER_TEST)); - - Assert.assertNotNull(updatedCertificateIssuer.credentials()); - Assert.assertNotNull(updatedCertificateIssuer.credentials().accountId()); - Assert.assertTrue(updatedCertificateIssuer.credentials().accountId().equals("account2")); - Assert.assertNull(updatedCertificateIssuer.credentials().password()); - - Assert.assertNotNull(updatedCertificateIssuer.organizationDetails()); - - IssuerBundle deletedCertificateIssuer = keyVaultClient.deleteCertificateIssuer(getVaultUri(), certificateIssuerName).getBody(); - - Assert.assertNotNull(deletedCertificateIssuer); - Assert.assertNotNull(deletedCertificateIssuer.provider()); - Assert.assertTrue(deletedCertificateIssuer.provider().equals(ISSUER_TEST)); - - Assert.assertNotNull(deletedCertificateIssuer.credentials()); - Assert.assertNotNull(deletedCertificateIssuer.credentials().accountId()); - Assert.assertTrue(deletedCertificateIssuer.credentials().accountId().equals("account2")); - Assert.assertNull(deletedCertificateIssuer.credentials().password()); - - Assert.assertNotNull(deletedCertificateIssuer.organizationDetails()); - - try { - keyVaultClient.getCertificateIssuer(getVaultUri(), certificateIssuerName); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("CertificateIssuerNotFound", e.getBody().error().code()); - } - } - - /** - * CRUD for Certificate contacts - * @throws Exception - */ - @Test - public void contactsCrudOperations() throws Exception { - // Create - Contact contact1 = new Contact(); - contact1.withName("James"); - contact1.withEmailAddress("james@contoso.com"); - contact1.withPhone("7777777777"); - - Contact contact2 = new Contact(); - contact2.withName("Ethan"); - contact2.withEmailAddress("ethan@contoso.com"); - contact2.withPhone("8888888888"); - - List contacts = new ArrayList(); - contacts.add(contact1); - contacts.add(contact2); - - Contacts certificateContacts = new Contacts(); - certificateContacts.withContactList(contacts); - Contacts createdCertificateContacts = keyVaultClient.setCertificateContacts(getVaultUri(), certificateContacts).getBody(); - Assert.assertNotNull(createdCertificateContacts); - Assert.assertNotNull(createdCertificateContacts.contactList()); - Assert.assertTrue(createdCertificateContacts.contactList().size() == 2); - Contact[] createContacts = createdCertificateContacts.contactList().toArray(new Contact[createdCertificateContacts.contactList().size()]); - Assert.assertTrue(createContacts[0].name().equalsIgnoreCase("James")); - Assert.assertTrue(createContacts[0].emailAddress().equalsIgnoreCase("james@contoso.com")); - Assert.assertTrue(createContacts[0].phone().equalsIgnoreCase("7777777777")); - Assert.assertTrue(createContacts[1].name().equalsIgnoreCase("Ethan")); - Assert.assertTrue(createContacts[1].emailAddress().equalsIgnoreCase("ethan@contoso.com")); - Assert.assertTrue(createContacts[1].phone().equalsIgnoreCase("8888888888")); - - // Get - Contacts retrievedCertificateContacts = keyVaultClient.getCertificateContacts(getVaultUri()).getBody(); - Assert.assertNotNull(retrievedCertificateContacts); - Assert.assertNotNull(retrievedCertificateContacts.contactList()); - Assert.assertTrue(retrievedCertificateContacts.contactList().size() == 2); - - // Delete - Contacts deletedCertificateContacts = keyVaultClient.deleteCertificateContacts(getVaultUri()).getBody(); - Assert.assertNotNull(deletedCertificateContacts); - Assert.assertNotNull(deletedCertificateContacts.contactList()); - Assert.assertTrue(deletedCertificateContacts.contactList().size() == 2); - - // Get after delete - try { - keyVaultClient.getCertificateContacts(getVaultUri()).getBody(); - } catch (KeyVaultErrorException e) { - Assert.assertNotNull(e.getBody().error()); - Assert.assertEquals("ContactsNotFound", e.getBody().error().code()); - } - } - - /** - * Polls on a certificate operation for completion. - * - * @throws Exception - */ - private static CertificateBundle pollOnCertificateOperation(CertificateOperation certificateOperation) - throws Exception { - - // Wait for enrollment to complete. We will wait for 200 seconds - int pendingPollCount = 0; - while (pendingPollCount < 21) { - String certificateName = certificateOperation.certificateOperationIdentifier().name(); - CertificateOperation pendingCertificateOperation = keyVaultClient - .getCertificateOperation(getVaultUri(), certificateName).getBody(); - if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)) { - Thread.sleep(10000); - pendingPollCount += 1; - continue; - } - - if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_COMPLETED)) { - return keyVaultClient.getCertificate(pendingCertificateOperation.target()).getBody(); - } - - throw new Exception(String.format( - "Polling on pending certificate returned an unexpected result. Error code = {1}, Error message = {2}", - pendingCertificateOperation.error().code(), - pendingCertificateOperation.error().message())); - } - - throw new Exception("Pending certificate processing delayed"); - } - - /** - * Extracts private key from PEM contents - * - * @throws InvalidKeySpecException - * @throws NoSuchAlgorithmException - */ - private static PrivateKey extractPrivateKeyFromPemContents(String pemContents) - throws InvalidKeySpecException, NoSuchAlgorithmException { - Matcher matcher = _privateKey.matcher(pemContents); - if (!matcher.find()) { - throw new IllegalArgumentException("No private key found in PEM contents."); - } - - byte[] privateKeyBytes = _base64.decode(matcher.group(1)); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); - KeyFactory keyFactory = KeyFactory.getInstance(ALGO_RSA); - PrivateKey privateKey = keyFactory.generatePrivate(keySpec); - return privateKey; - } - - /** - * Extracts certificates from PEM contents - * - * @throws CertificateException - * @throws IOException - */ - private static List extractCertificatesFromPemContents(String pemContents) - throws CertificateException, IOException { - Matcher matcher = _certificate.matcher(pemContents); - if (!matcher.find()) { - throw new IllegalArgumentException("No certificate found in PEM contents."); - } - - List result = new ArrayList(); - int offset = 0; - while (true) { - if (!matcher.find(offset)) { - break; - } - byte[] certBytes = _base64.decode(matcher.group(1)); - ByteArrayInputStream certStream = new ByteArrayInputStream(certBytes); - CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certStream); - certStream.close(); - - result.add(x509Certificate); - offset = matcher.end(); - } - - return result; - } - - /** - * Verify a RSA key pair with a simple encrypt/decrypt test. - * - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - */ - private static void verifyRSAKeyPair(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchPaddingException, - InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - // Validate algorithm is RSA - Assert.assertTrue(keyPair.getPublic().getAlgorithm().equals(ALGO_RSA)); - Assert.assertTrue(keyPair.getPrivate().getAlgorithm().equals(ALGO_RSA)); - - // Generate an array of 10 random bytes - byte[] plainData = new byte[10]; - Random random = new Random(); - random.nextBytes(plainData); - - // Encrypt using the public key - Cipher encryptCipher = Cipher.getInstance(ALGO_RSA); - encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); - byte[] encryptedData = encryptCipher.doFinal(plainData); - - // Decrypt using the private key - Cipher decryptCipher = Cipher.getInstance(ALGO_RSA); - decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); - byte[] decryptedData = decryptCipher.doFinal(encryptedData); - - // Validate plainData is equal to decryptedData - Assert.assertArrayEquals(plainData, decryptedData); - } - - private String toHexString(byte[] x5t) { - - if(x5t == null) - return ""; - - StringBuilder hexString = new StringBuilder(); - for (int i = 0; i < x5t.length; i++) { - String hex = Integer.toHexString(0xFF & x5t[i]); - if (hex.length() == 1) { - hexString.append('0'); - } - hexString.append(hex); - } - - return hexString.toString().replace("-", ""); - } + return hexString.toString().replace("-", ""); + } + + private void validateCertificateBundle(CertificateBundle certificateBundle, CertificatePolicy certificatePolicy) { + Assert.assertNotNull(certificateBundle); + Assert.assertNotNull(certificateBundle.id()); + Assert.assertNotNull(certificateBundle.keyIdentifier()); + Assert.assertNotNull(certificateBundle.secretIdentifier()); + Assert.assertNotNull(certificateBundle.x509Thumbprint()); + + if (certificatePolicy != null) { + Assert.assertNotNull(certificateBundle.policy()); + Assert.assertNotNull(certificateBundle.policy().issuerReference()); + Assert.assertNotNull(certificateBundle.policy().issuerReference().name()); + if(certificatePolicy.issuerReference() != null) { + Assert.assertTrue(certificateBundle.policy().issuerReference().name().equalsIgnoreCase(certificatePolicy.issuerReference().name())); + } + } + } + + private X509Certificate loadCerToX509Certificate(CertificateBundle certificateBundle) throws CertificateException, IOException { + Assert.assertNotNull(certificateBundle.cer()); + ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer()); + CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); + X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); + cerStream.close(); + return x509Certificate; + } + + private void validateCertificateIssuer(IssuerBundle expecred, IssuerBundle actual) { + Assert.assertNotNull(actual); + Assert.assertNotNull(actual.provider()); + Assert.assertTrue(actual.provider().equals(expecred.provider())); + + Assert.assertNotNull(actual.credentials()); + Assert.assertNotNull(actual.credentials().accountId()); + Assert.assertTrue(actual.credentials().accountId().equals(expecred.credentials().accountId())); + Assert.assertNull(actual.credentials().password()); + + Assert.assertNotNull(actual.organizationDetails()); + } + + private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate, String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + String defaultAlias = Collections.list(keyStore.aliases()).get(0); + X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias); + Assert.assertNotNull(secretCertificate); + Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() + .equals(x509Certificate.getSubjectX500Principal().getName())); + Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() + .equals(x509Certificate.getIssuerX500Principal().getName())); + Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); + + + // Validate the key in the KeyStore + Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray()); + Assert.assertNotNull(secretKey); + Assert.assertTrue(secretKey instanceof PrivateKey); + PrivateKey secretPrivateKey = (PrivateKey) secretKey; + + // Create a KeyPair with the private key from the KeyStore and public + // key from the certificate to verify they match + KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); + Assert.assertNotNull(keyPair); + verifyRSAKeyPair(keyPair); + } + + private void validateCertificateIssuer(IssuerBundle issuer, String issuerName) { + Assert.assertNotNull(issuer); + Assert.assertNotNull(issuer.issuerIdentifier()); + Assert.assertNotNull(issuer.issuerIdentifier().name()); + Assert.assertTrue(issuer.issuerIdentifier().name().equalsIgnoreCase(issuerName)); + } + + private KeyStore loadSecretToKeyStore(SecretBundle secret, String secretPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { + ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value())); + KeyStore keyStore = KeyStore.getInstance(PKCS12); + keyStore.load(secretStream, secretPassword.toCharArray()); + secretStream.close(); + return keyStore; + } + + private void validatePem(CertificateBundle certificateBundle, String subjectName) throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + // Load the CER part into X509Certificate object + X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle); + + Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); + Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); + + // Retrieve the secret backing the certificate + SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + String secretValue = secret.value(); + + // Extract private key from PEM + PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue); + Assert.assertNotNull(secretPrivateKey); + + // Extract certificates from PEM + List certificates = extractCertificatesFromPemContents(secretValue); + Assert.assertNotNull(certificates); + Assert.assertTrue(certificates.size() == 1); + + // has the public key corresponding to the private key. + X509Certificate secretCertificate = certificates.get(0); + Assert.assertNotNull(secretCertificate); + Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() + .equals(x509Certificate.getSubjectX500Principal().getName())); + Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() + .equals(x509Certificate.getIssuerX500Principal().getName())); + Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); + + // Create a KeyPair with the private key from the KeyStore and public + // key from the certificate to verify they match + KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); + Assert.assertNotNull(keyPair); + verifyRSAKeyPair(keyPair); + } } diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java index 08ff519858b73..f227d9f5ca3cb 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -48,6 +48,7 @@ import com.microsoft.azure.keyvault.requests.ImportKeyRequest; import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; import com.microsoft.azure.keyvault.models.JsonWebKey; +import com.microsoft.azure.keyvault.models.KeyAttributes; import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; @@ -64,15 +65,30 @@ public void transparentAuthentication() throws Exception { // Create a key on a vault. { - KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA").build()).getBody(); - validateRsaKeyBundle(bundle, getVaultUri(), KEY_NAME, "RSA", null); + Map tags = new HashMap(); + tags.put("foo", "baz"); + List keyOps = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); + KeyAttributes attribute = (KeyAttributes) new KeyAttributes() + .withEnabled(true) + .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) + .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); + + KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest + .Builder(getVaultUri(), KEY_NAME, "RSA") + .withAttributes(attribute) + .withKeyOperations(keyOps) + .withKeySize(2048) + .withTags(tags) + .build()).getBody(); + + validateRsaKeyBundle(bundle, getVaultUri(), KEY_NAME, "RSA", keyOps, attribute); } // Create a key on a different vault. Key Vault Data Plane returns 401, // which must be transparently handled by KeyVaultCredentials. { KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getSecondaryVaultUri(), KEY_NAME, "RSA").build()).getBody(); - validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, "RSA", null); + validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, "RSA", null, null); } } @@ -92,13 +108,24 @@ public void importKeyOperation() throws Exception { } private void checkImportOperation(KeyBundle keyBundle, boolean importToHardware) throws Exception { + KeyAttributes attribute = (KeyAttributes) new KeyAttributes() + .withEnabled(true) + .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) + .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); + + Map tags = new HashMap(); + tags.put("foo", "baz"); + JsonWebKey importedJwk = keyBundle.key(); KeyBundle importResultBundle = keyVaultClient.importKey( - new ImportKeyRequest - .Builder(getVaultUri(), KEY_NAME, keyBundle.key()) - .withHsm(importToHardware) - .build()).getBody(); - validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? "RSA-HSM" : "RSA", importedJwk.keyOps()); + new ImportKeyRequest + .Builder(getVaultUri(), KEY_NAME, keyBundle.key()) + .withHsm(importToHardware) + .withAttributes(attribute) + .withTags(tags) + .build()).getBody(); + + validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? "RSA-HSM" : "RSA", importedJwk.keyOps(), attribute); checkEncryptDecryptSequence(importedJwk, importResultBundle); } @@ -151,7 +178,7 @@ public void crudOperations() throws Exception { { // Create key createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA").build()).getBody(); - validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, "RSA", null); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, "RSA", null, null); } // Key identifier. @@ -192,9 +219,9 @@ public void crudOperations() throws Exception { // First we create a bundle with the modified attributes. createdBundle.attributes().withExpires(new DateTime() - .withMonthOfYear(2) - .withDayOfMonth(1) - .withYear(2050)); + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2050)); List key_ops = Arrays.asList("encrypt", "decrypt"); Map tags = new HashMap(); tags.put("foo", "baz"); @@ -203,12 +230,12 @@ public void crudOperations() throws Exception { // Perform the operation. KeyBundle updatedBundle = keyVaultClient.updateKey( - new UpdateKeyRequest - .Builder(createdBundle.key().kid()) - .withKeyOperations(key_ops) - .withAttributes(createdBundle.attributes()) - .withTags(createdBundle.tags()) - .build()).getBody(); + new UpdateKeyRequest + .Builder(createdBundle.key().kid()) + .withKeyOperations(key_ops) + .withAttributes(createdBundle.attributes()) + .withTags(createdBundle.tags()) + .build()).getBody(); compareKeyBundles(createdBundle, updatedBundle); @@ -220,24 +247,24 @@ public void crudOperations() throws Exception { // Update key using vault and key name. // First we create a bundle with the modified attributes. - createdBundle.attributes().withNotBefore(new DateTime() - .withMonthOfYear(2) - .withDayOfMonth(1) - .withYear(2000)); + createdBundle.attributes().withNotBefore(new DateTime() + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2000)); List key_ops = Arrays.asList("sign", "verify"); createdBundle.key().withKeyOps(key_ops); Map tags = new HashMap(); tags.put("foo", "baz"); createdBundle.withTags(tags); - // Perform the operation. + // Perform the operation. KeyBundle updatedBundle = keyVaultClient.updateKey( - new UpdateKeyRequest - .Builder(getVaultUri(), KEY_NAME) - .withKeyOperations(key_ops) - .withAttributes(createdBundle.attributes()) - .withTags(createdBundle.tags()) - .build()).getBody(); + new UpdateKeyRequest + .Builder(getVaultUri(), KEY_NAME) + .withKeyOperations(key_ops) + .withAttributes(createdBundle.attributes()) + .withTags(createdBundle.tags()) + .build()).getBody(); compareKeyBundles(createdBundle, updatedBundle); } @@ -251,7 +278,7 @@ public void crudOperations() throws Exception { { // Expects a key not found try { - keyVaultClient.getKey(keyId.baseIdentifier()); + keyVaultClient.getKey(keyId.baseIdentifier()); } catch (KeyVaultErrorException e) { Assert.assertNotNull(e.getBody().error()); Assert.assertEquals("KeyNotFound", e.getBody().error().code()); @@ -268,9 +295,9 @@ public void backupRestore() throws Exception { // Creates a key { createdBundle = keyVaultClient.createKey( - new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA") - .build()).getBody(); - validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, "RSA", null); + new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA") + .build()).getBody(); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, "RSA", null, null); } // Creates a backup of key. @@ -316,7 +343,7 @@ public void listKeys() throws Exception { } } - PagedList listResult = keyVaultClient.getKeys(getVaultUri(), PAGELIST_MAX_KEYS).getBody(); + PagedList listResult = keyVaultClient.listKeys(getVaultUri(), PAGELIST_MAX_KEYS).getBody(); Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().getItems().size()); HashSet toDelete = new HashSet(); @@ -330,14 +357,14 @@ public void listKeys() throws Exception { Assert.assertEquals(0, keys.size()); for (String name : toDelete) { - try{ - keyVaultClient.deleteKey(getVaultUri(), name); - } - catch(KeyVaultErrorException e){ - // Ignore forbidden exception for certificate keys that cannot be deleted - if(!e.getBody().error().code().equals("Forbidden")) - throw e; - } + try{ + keyVaultClient.deleteKey(getVaultUri(), name); + } + catch(KeyVaultErrorException e){ + // Ignore forbidden exception for certificate keys that cannot be deleted + if(!e.getBody().error().code().equals("Forbidden")) + throw e; + } } } @@ -364,20 +391,13 @@ public void listKeyVersions() throws Exception { } } - PagedList listResult = keyVaultClient.getKeyVersions(getVaultUri(), KEY_NAME, MAX_KEYS).getBody(); + PagedList listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME, MAX_KEYS).getBody(); //TODO bug: Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.getKeyVersions(getVaultUri(), KEY_NAME).getBody(); + listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME).getBody(); - for (;;) { - for (KeyItem item : listResult) { - keys.remove(item.kid()); - } - String nextLink = listResult.nextPageLink(); - if (nextLink == null) { - break; - } - keyVaultClient.getKeyVersionsNext(nextLink).getBody(); + for (KeyItem item : listResult) { + keys.remove(item.kid()); } Assert.assertEquals(0, keys.size()); @@ -400,7 +420,7 @@ public void encryptDecryptOperations() throws Exception { // encrypt and decrypt using kid WO version { - result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); cipherText = result.result(); result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); @@ -409,7 +429,7 @@ public void encryptDecryptOperations() throws Exception { // encrypt and decrypt using full kid { - result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); cipherText = result.result(); result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); @@ -432,7 +452,7 @@ public void wrapUnwrapOperations() throws Exception { // wrap and unwrap using kid WO version { - result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); cipherText = result.result(); result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); @@ -441,7 +461,7 @@ public void wrapUnwrapOperations() throws Exception { // wrap and unwrap using full kid { - result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); cipherText = result.result(); result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); @@ -468,7 +488,7 @@ public void signVerifyOperations() throws Exception { // Using kid WO version { - result = keyVaultClient.sign(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest).getBody(); + result = keyVaultClient.sign(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest).getBody(); signature = result.result(); verifyResult = keyVaultClient.verify(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest, signature).getBody(); @@ -495,18 +515,18 @@ private static JsonWebKey importTestKey() throws Exception { key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT, JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY, JsonWebKeyOperation.WRAP, JsonWebKeyOperation.UNWRAP)); keyBundle = keyVaultClient.importKey( - new ImportKeyRequest - .Builder(getVaultUri(), KEY_NAME, key) - .withHsm(false) - .build()).getBody(); + new ImportKeyRequest + .Builder(getVaultUri(), KEY_NAME, key) + .withHsm(false) + .build()).getBody(); - validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, "RSA", null); + validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, "RSA", null, null); return keyBundle.key(); } private static KeyPair getTestKeyMaterial() throws Exception { - return getWellKnownKey(); + return getWellKnownKey(); } private static KeyPair getWellKnownKey() throws Exception { @@ -526,7 +546,7 @@ private static KeyPair getWellKnownKey() throws Exception { return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); } - private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, String kty, List key_ops) throws Exception { + private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, String kty, List key_ops, KeyAttributes attributes) throws Exception { String prefix = vault + "/keys/" + keyName + "/"; String kid = bundle.key().kid(); Assert.assertTrue( @@ -540,16 +560,18 @@ private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String } Assert.assertNotNull("\"created\" should not be null.", bundle.attributes().created()); Assert.assertNotNull("\"updated\" should not be null.", bundle.attributes().updated()); + + compareAttributes(attributes, bundle.attributes()); } private void compareKeyBundles(KeyBundle expected, KeyBundle actual) { - Assert.assertTrue(expected.key().toString().equals(actual.key().toString())); - Assert.assertEquals(expected.attributes().enabled(), actual.attributes().enabled()); - Assert.assertEquals(expected.attributes().expires(), actual.attributes().expires()); - Assert.assertEquals(expected.attributes().notBefore(), actual.attributes().notBefore()); - if(expected.tags() != null || actual.tags() != null) - Assert.assertTrue(expected.tags().equals(actual.tags())); - } + Assert.assertTrue(expected.key().toString().equals(actual.key().toString())); + Assert.assertEquals(expected.attributes().enabled(), actual.attributes().enabled()); + Assert.assertEquals(expected.attributes().expires(), actual.attributes().expires()); + Assert.assertEquals(expected.attributes().notBefore(), actual.attributes().notBefore()); + if(expected.tags() != null || actual.tags() != null) + Assert.assertTrue(expected.tags().equals(actual.tags())); + } } diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java index be6906865cd25..2ebb0c791a977 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java @@ -25,6 +25,7 @@ import org.junit.After; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -37,6 +38,7 @@ import com.microsoft.aad.adal4j.ClientCredential; import com.microsoft.azure.keyvault.KeyVaultClient; import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials; +import com.microsoft.azure.keyvault.models.Attributes; public class KeyVaultClientIntegrationTestBase { @@ -95,7 +97,7 @@ public String doAuthenticate(String authorization, String resource, String scope private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception { String clientId = System.getenv("arm.clientid"); - + if (clientId == null) { throw new Exception("Please inform arm.clientid in the environment settings."); } @@ -136,6 +138,14 @@ private static AuthenticationResult getAccessToken(String authorization, String return result; } + protected static void compareAttributes(Attributes expectedAttributes, Attributes actualAttribute) { + if(expectedAttributes != null) { + Assert.assertEquals(expectedAttributes.enabled(), actualAttribute.enabled()); + Assert.assertEquals(expectedAttributes.expires(), actualAttribute.expires()); + Assert.assertEquals(expectedAttributes.notBefore(), actualAttribute.notBefore()); + } + } + protected static ObjectWriter jsonWriter; protected static ObjectReader jsonReader; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java index aac73d56cf5c1..7378e9ebc9bee 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java @@ -26,6 +26,7 @@ import org.junit.Test; import com.microsoft.azure.keyvault.models.KeyVaultErrorException; +import com.microsoft.azure.keyvault.models.SecretAttributes; import com.microsoft.azure.keyvault.models.SecretBundle; import com.microsoft.azure.PagedList; import com.microsoft.azure.keyvault.SecretIdentifier; @@ -45,17 +46,30 @@ public void transparentAuthentication() throws Exception { // Create a secret on a vault. { - SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); - validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, null); + SecretAttributes attributes = (SecretAttributes) new SecretAttributes() + .withEnabled(true) + .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) + .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); + Map tags = new HashMap(); + tags.put("foo", "baz"); + String contentType = "contentType"; + + SecretBundle secret = keyVaultClient.setSecret( + new SetSecretRequest + .Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE) + .withAttributes(attributes) + .withContentType(contentType) + .withTags(tags) + .build()).getBody(); + validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, contentType, attributes); } // Create a secret on a different vault. Secret Vault Data Plane returns // 401, which must be transparently handled by KeyVaultCredentials. { - SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); - validateSecret(secret, getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE, null); + SecretBundle secret = keyVaultClient.setSecret( + new SetSecretRequest.Builder(getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); + validateSecret(secret, getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); } } @@ -63,12 +77,12 @@ public void transparentAuthentication() throws Exception { @Test public void crudOperations() throws Exception { - SecretBundle secret; + SecretBundle secret; { // Create secret - secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); - validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, null); + secret = keyVaultClient.setSecret( + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); + validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); } // Secret identifier. @@ -76,47 +90,47 @@ public void crudOperations() throws Exception { { // Get secret using kid WO version - SecretBundle readBundle = keyVaultClient.getSecret(secretId.baseIdentifier()).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(secretId.baseIdentifier()).getBody(); compareSecrets(secret, readBundle); } { // Get secret using full kid as defined in the bundle - SecretBundle readBundle = keyVaultClient.getSecret(secret.id()).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(secret.id()).getBody(); compareSecrets(secret, readBundle); } { // Get secret using vault and secret name. - SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME).getBody(); compareSecrets(secret, readBundle); } { // Get secret using vault, secret name and version. - SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME, secretId.version()).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME, secretId.version()).getBody(); compareSecrets(secret, readBundle); } { - secret.attributes().withExpires(new DateTime() - .withMonthOfYear(2) - .withDayOfMonth(1) - .withYear(2050)); - Map tags = new HashMap(); - tags.put("foo", "baz"); - secret.withTags(tags) - .withContentType("application/html") - .withValue(null); // The value doesn't get updated - + secret.attributes().withExpires(new DateTime() + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2050)); + Map tags = new HashMap(); + tags.put("foo", "baz"); + secret.withTags(tags) + .withContentType("application/html") + .withValue(null); // The value doesn't get updated + // Update secret using the kid as defined in the bundle SecretBundle updatedSecret = keyVaultClient.updateSecret( - new UpdateSecretRequest - .Builder(secret.id()) - .withContentType(secret.contentType()) - .withAttributes(secret.attributes()) - .withTags(secret.tags()) - .build()).getBody(); + new UpdateSecretRequest + .Builder(secret.id()) + .withContentType(secret.contentType()) + .withAttributes(secret.attributes()) + .withTags(secret.tags()) + .build()).getBody(); compareSecrets(secret, updatedSecret); // Subsequent operations must use the updated bundle for comparison. @@ -126,37 +140,42 @@ public void crudOperations() throws Exception { { // Update secret using vault and secret name. - secret.attributes().withNotBefore(new DateTime() - .withMonthOfYear(2) - .withDayOfMonth(1) - .withYear(2000)); - Map tags = new HashMap(); - tags.put("rex", "woof"); - secret.withTags(tags) - .withContentType("application/html"); + secret.attributes().withNotBefore(new DateTime() + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2000)); + Map tags = new HashMap(); + tags.put("rex", "woof"); + secret.withTags(tags) + .withContentType("application/html"); // Perform the operation. SecretBundle updatedSecret = keyVaultClient.updateSecret( - new UpdateSecretRequest - .Builder(getVaultUri(), SECRET_NAME) - .withContentType(secret.contentType()) - .withAttributes(secret.attributes()) - .withTags(secret.tags()) - .build()).getBody(); + new UpdateSecretRequest + .Builder(getVaultUri(), SECRET_NAME) + .withVersion(secret.secretIdentifier().version()) + .withContentType(secret.contentType()) + .withAttributes(secret.attributes()) + .withTags(secret.tags()) + .build()).getBody(); compareSecrets(secret, updatedSecret); + validateSecret(updatedSecret, + secret.secretIdentifier().vault(), + secret.secretIdentifier().name(), + null, secret.contentType(), secret.attributes()); } { // Delete secret - SecretBundle deleteBundle = keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME).getBody(); + SecretBundle deleteBundle = keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME).getBody(); compareSecrets(secret, deleteBundle); } { // Expects a secret not found try { - keyVaultClient.getSecret(secretId.baseIdentifier()); + keyVaultClient.getSecret(secretId.baseIdentifier()); } catch (KeyVaultErrorException e) { Assert.assertNotNull(e.getBody().error().code()); Assert.assertEquals("SecretNotFound", e.getBody().error().code()); @@ -165,7 +184,7 @@ public void crudOperations() throws Exception { } - @Test + @Test public void listSecrets() throws Exception { HashSet secrets = new HashSet(); @@ -174,7 +193,7 @@ public void listSecrets() throws Exception { for (;;) { try { SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME + i, SECRET_VALUE).build()).getBody(); + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME + i, SECRET_VALUE).build()).getBody(); SecretIdentifier id = new SecretIdentifier(secret.id()); secrets.add(id.baseIdentifier()); break; @@ -190,7 +209,7 @@ public void listSecrets() throws Exception { } } - PagedList listResult = keyVaultClient.getSecrets(getVaultUri(), PAGELIST_MAX_SECRETS).getBody(); + PagedList listResult = keyVaultClient.listSecrets(getVaultUri(), PAGELIST_MAX_SECRETS).getBody(); Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().getItems().size()); HashSet toDelete = new HashSet(); @@ -204,14 +223,14 @@ public void listSecrets() throws Exception { Assert.assertEquals(0, secrets.size()); for (String secretName : toDelete) { - try{ - keyVaultClient.deleteSecret(getVaultUri(), secretName); - } - catch(KeyVaultErrorException e){ - // Ignore forbidden exception for certificate secrets that cannot be deleted - if(!e.getBody().error().code().equals("Forbidden")) - throw e; - } + try{ + keyVaultClient.deleteSecret(getVaultUri(), secretName); + } + catch(KeyVaultErrorException e){ + // Ignore forbidden exception for certificate secrets that cannot be deleted + if(!e.getBody().error().code().equals("Forbidden")) + throw e; + } } } @@ -224,7 +243,7 @@ public void listSecretVersions() throws Exception { for (;;) { try { SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); secrets.add(secret.id()); break; } catch (KeyVaultErrorException e) { @@ -239,19 +258,12 @@ public void listSecretVersions() throws Exception { } } - PagedList listResult = keyVaultClient.getSecretVersions(getVaultUri(), SECRET_NAME, PAGELIST_MAX_SECRETS).getBody(); + PagedList listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME, PAGELIST_MAX_SECRETS).getBody(); Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.getSecretVersions(getVaultUri(), SECRET_NAME).getBody(); - for (;;) { - for (SecretItem item : listResult) { - secrets.remove(item.id()); - } - String nextLink = listResult.nextPageLink(); - if (nextLink == null) { - break; - } - keyVaultClient.getSecretVersionsNext(nextLink).getBody(); + listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME).getBody(); + for (SecretItem item : listResult) { + secrets.remove(item.id()); } Assert.assertEquals(0, secrets.size()); @@ -259,7 +271,7 @@ public void listSecretVersions() throws Exception { keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME); } - private static void validateSecret(SecretBundle secret, String vault, String name, String value, String contentType) throws Exception { + private static void validateSecret(SecretBundle secret, String vault, String name, String value, String contentType, SecretAttributes attributes) throws Exception { String prefix = vault + "/secrets/" + name + "/"; String id = secret.id(); Assert.assertTrue( // @@ -271,17 +283,19 @@ private static void validateSecret(SecretBundle secret, String vault, String nam } Assert.assertNotNull("\"created\" should not be null.", secret.attributes().created()); Assert.assertNotNull("\"updated\" should not be null.", secret.attributes().updated()); + + compareAttributes(attributes, secret.attributes()); } private void compareSecrets(SecretBundle expected, SecretBundle actual) { - Assert.assertEquals(expected.contentType(), actual.contentType()); - Assert.assertEquals(expected.id(), actual.id()); - Assert.assertEquals(expected.value(), actual.value()); - Assert.assertEquals(expected.attributes().enabled(), actual.attributes().enabled()); - Assert.assertEquals(expected.attributes().expires(), actual.attributes().expires()); - Assert.assertEquals(expected.attributes().notBefore(), actual.attributes().notBefore()); - if(expected.tags() != null || actual.tags() != null) - Assert.assertTrue(expected.tags().equals(actual.tags())); - } + Assert.assertEquals(expected.contentType(), actual.contentType()); + Assert.assertEquals(expected.id(), actual.id()); + Assert.assertEquals(expected.value(), actual.value()); + Assert.assertEquals(expected.attributes().enabled(), actual.attributes().enabled()); + Assert.assertEquals(expected.attributes().expires(), actual.attributes().expires()); + Assert.assertEquals(expected.attributes().notBefore(), actual.attributes().notBefore()); + if(expected.tags() != null || actual.tags() != null) + Assert.assertTrue(expected.tags().equals(actual.tags())); + } } From 9b051c8ea96ae60cb3f453b69fabb49c02ac06bb Mon Sep 17 00:00:00 2001 From: Hervey Wilson Date: Mon, 15 Aug 2016 16:35:42 -0700 Subject: [PATCH 02/14] Java Cryptography Test Case update --- .../azure/keyvault/cryptography/RsaKey.java | 19 + .../test/AesCbcBCProviderTest.java | 120 +---- .../test/AesCbcHmacShaBCProviderTest.java | 17 + .../cryptography/test/AesCbcHmacShaTest.java | 59 +-- ...faultProviderTest.java => AesCbcTest.java} | 61 +-- .../test/AesKwBCProviderTest.java | 261 +---------- ...efaultProviderTest.java => AesKwTest.java} | 135 ++---- .../test/RsaKeyBCProviderTest.java | 16 + .../cryptography/test/RsaKeyTest.java | 30 +- .../test/SymmetricKeyBCProviderTest.java | 326 +------------- .../test/SymmetricKeyBaseTest.java | 423 ++++++++++++++++++ .../test/SymmetricKeyDefaultProviderTest.java | 399 +---------------- 12 files changed, 576 insertions(+), 1290 deletions(-) create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java rename azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/{AesCbcDefaultProviderTest.java => AesCbcTest.java} (61%) rename azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/{AesKwDefaultProviderTest.java => AesKwTest.java} (60%) create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java index d8fe513c31c7b..b56511a99205d 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java @@ -22,6 +22,7 @@ import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; +import java.security.Provider; import java.security.interfaces.RSAPublicKey; import org.apache.commons.lang3.NotImplementedException; @@ -52,6 +53,8 @@ public RsaKey(String kid) throws NoSuchAlgorithmException { public RsaKey(String kid, int keySize) throws NoSuchAlgorithmException { + this(kid, keySize, null); + /* if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); } @@ -62,6 +65,22 @@ public RsaKey(String kid, int keySize) throws NoSuchAlgorithmException { _keyPair = generator.generateKeyPair(); _kid = kid; + */ + } + + public RsaKey(String kid, int keySize, Provider provider) throws NoSuchAlgorithmException { + + if (Strings.isNullOrWhiteSpace(kid)) { + throw new IllegalArgumentException("kid"); + } + + final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider); + + generator.initialize(keySize); + + _keyPair = generator.generateKeyPair(); + _kid = kid; + } public RsaKey(String kid, KeyPair keyPair) { diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java index c7d9c96b36702..043b2b54808be 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java @@ -1,132 +1,18 @@ package com.microsoft.azure.keyvault.cryptography.test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; import java.security.Provider; -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; -import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; - -public class AesCbcBCProviderTest { - private Provider _provider = null; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } +public class AesCbcBCProviderTest extends AesCbcTest { @Before public void setUp() throws Exception { try { - _provider = (Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance(); - } catch (ClassNotFoundException ex) { - throw new RuntimeException(ex.getMessage()); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex.getMessage()); - } catch (InstantiationException ex) { + super.setProvider((Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance()); + } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } - @After - public void tearDown() throws Exception { - } - - @Test - public void testAes128Cbc() { - // Arrange: These values are taken from Appendix B of the JWE - // specification at - // https://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-40#appendix-B - // Since the values were intended for use with AES128-CBC-HMAC-SHA2 we - // actually take the realCEK from the second half of the CEK data below - // in order - // that the encrypted result will match the ED value from the example. - byte[] CEK = { 4, (byte) 211, 31, (byte) 197, 84, (byte) 157, (byte) 252, (byte) 254, 11, 100, (byte) 157, (byte) 250, 63, (byte) 170, 106, (byte) 206, 107, 124, (byte) 212, 45, 111, 107, 9, (byte) 219, (byte) 200, (byte) 177, 0, (byte) 240, (byte) 143, (byte) 156, 44, (byte) 207 }; - byte[] PLAIN = { 76, 105, 118, 101, 32, 108, 111, 110, 103, 32, 97, 110, 100, 32, 112, 114, 111, 115, 112, 101, 114, 46 }; - byte[] IV = { 3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101 }; - //byte[] AUTH = { 101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 66, 77, 84, 73, 52, 83, 49, 99, 105, 76, 67, 74, 108, 98, 109, 77, 105, 79, 105, 74, 66, 77, 84, 73, 52, 81, 48, 74, 68, 76, 85, 104, 84, 77, 106, 85, 50, 73, 110, 48 }; - byte[] ED = { 40, 57, 83, (byte) 181, 119, 33, (byte) 133, (byte) 148, (byte) 198, (byte) 185, (byte) 243, 24, (byte) 152, (byte) 230, 6, 75, (byte) 129, (byte) 223, 127, 19, (byte) 210, 82, (byte) 183, (byte) 230, (byte) 168, 33, (byte) 215, 104, (byte) 143, 112, 56, 102 }; - //byte[] TAG = { 83, 73, (byte) 191, 98, 104, (byte) 205, (byte) 211, (byte) 128, (byte) 201, (byte) 189, (byte) 199, (byte) 133, 32, 38, (byte) 194, 85 }; - - Aes128Cbc algo = new Aes128Cbc(); - byte[] realCEK = new byte[128 >> 3]; - byte[] encrypted = null; - - // Take the second half of CEK as the AES key - System.arraycopy(CEK, 128 >> 3, realCEK, 0, 128 >> 3); - - ICryptoTransform encryptor = null; - try { - encryptor = algo.CreateEncryptor(realCEK, IV, null, _provider); - } catch (InvalidKeyException e1) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e1) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e1) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e1) { - fail("InvalidAlgorithmParameterException"); - } - - try { - encrypted = encryptor.doFinal(PLAIN); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - ICryptoTransform decryptor = null; - try { - decryptor = algo.CreateDecryptor(realCEK, IV, null, _provider); - } catch (InvalidKeyException e1) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e1) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e1) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e1) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] decrypted = null; - - try { - decrypted = decryptor.doFinal(encrypted); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(PLAIN, decrypted); - assertArrayEquals(ED, encrypted); - } } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java new file mode 100644 index 0000000000000..5c7e07a273474 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java @@ -0,0 +1,17 @@ +package com.microsoft.azure.keyvault.cryptography.test; + +import java.security.Provider; + +import org.junit.Before; + +public class AesCbcHmacShaBCProviderTest extends AesCbcHmacShaTest { + + @Before + public void setUp() throws Exception { + try { + super.setProvider((Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance()); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + } +} diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java index 211f3116bd0bc..4783152229b1d 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java @@ -3,13 +3,7 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; +import java.security.Provider; import org.junit.After; import org.junit.AfterClass; @@ -22,6 +16,8 @@ import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128CbcHmacSha256; public class AesCbcHmacShaTest { + + private Provider _provider = null; @BeforeClass public static void setUpBeforeClass() throws Exception { @@ -33,11 +29,16 @@ public static void tearDownAfterClass() throws Exception { @Before public void setUp() throws Exception { + setProvider(null); } @After public void tearDown() throws Exception { } + + protected void setProvider(Provider provider) { + _provider = null; + } @Test public void testAes128CbcHmacSha256() { @@ -59,15 +60,9 @@ public void testAes128CbcHmacSha256() { byte[] tag = null; try { - transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(CEK, IV, AUTH); - } catch (InvalidKeyException e1) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e1) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e1) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e1) { - fail("InvalidAlgorithmParameterException"); + transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(CEK, IV, AUTH, _provider); + } catch (Exception e) { + fail(e.getMessage()); } try { @@ -77,41 +72,23 @@ public void testAes128CbcHmacSha256() { assertArrayEquals(ED, encrypted); assertArrayEquals(TAG, tag); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } ICryptoTransform decryptor = null; try { - decryptor = algo.CreateDecryptor(CEK, IV, AUTH); - } catch (InvalidKeyException e1) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e1) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e1) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e1) { - fail("InvalidAlgorithmParameterException"); + decryptor = algo.CreateDecryptor(CEK, IV, AUTH, _provider); + } catch (Exception e) { + fail(e.getMessage()); } byte[] decrypted = null; try { decrypted = decryptor.doFinal(encrypted); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcDefaultProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java similarity index 61% rename from azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcDefaultProviderTest.java rename to azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java index 947ef7cddfc74..53286b5471690 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcDefaultProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java @@ -3,13 +3,7 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; +import java.security.Provider; import org.junit.After; import org.junit.AfterClass; @@ -20,8 +14,10 @@ import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; -public class AesCbcDefaultProviderTest { +public class AesCbcTest { + private Provider _provider = null; + @BeforeClass public static void setUpBeforeClass() throws Exception { } @@ -32,11 +28,16 @@ public static void tearDownAfterClass() throws Exception { @Before public void setUp() throws Exception { + setProvider(null); } @After public void tearDown() throws Exception { } + + protected void setProvider(Provider provider) { + _provider = provider; + } @Test public void testAes128Cbc() { @@ -63,54 +64,30 @@ public void testAes128Cbc() { ICryptoTransform encryptor = null; try { - encryptor = algo.CreateEncryptor(realCEK, IV, null); - } catch (InvalidKeyException e1) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e1) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e1) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e1) { - fail("InvalidAlgorithmParameterException"); + encryptor = algo.CreateEncryptor(realCEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); } try { encrypted = encryptor.doFinal(PLAIN); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } ICryptoTransform decryptor = null; try { - decryptor = algo.CreateDecryptor(realCEK, IV, null); - } catch (InvalidKeyException e1) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e1) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e1) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e1) { - fail("InvalidAlgorithmParameterException"); + decryptor = algo.CreateDecryptor(realCEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); } byte[] decrypted = null; try { decrypted = decryptor.doFinal(encrypted); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java index e1e7ce50c53f7..480db6f2e8966 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java @@ -18,272 +18,17 @@ package com.microsoft.azure.keyvault.cryptography.test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; import java.security.Provider; -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; -import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw; -import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw128; -import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw192; -import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw256; - -public class AesKwBCProviderTest { - - private Provider _provider = null; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } +public class AesKwBCProviderTest extends AesKwTest { @Before public void setUp() throws Exception { try { - _provider = (Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance(); - } catch (ClassNotFoundException ex) { - throw new RuntimeException(ex.getMessage()); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex.getMessage()); - } catch (InstantiationException ex) { + super.setProvider((Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance()); + } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } - - @After - public void tearDown() throws Exception { - } - - @Test - public void KeyVault_AesKw128() { - // Arrange - byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - 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[] 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 }; - - AesKw kw = new AesKw128(); - - ICryptoTransform encryptor = null; - - try { - encryptor = kw.CreateEncryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] encrypted = null; - - try { - encrypted = encryptor.doFinal(CEK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - ICryptoTransform decryptor = null; - - try { - decryptor = kw.CreateDecryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] decrypted = null; - - try { - decrypted = decryptor.doFinal(EK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - - @Test - public void KeyVault_AesKw192() { - // Arrange - 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 }; - 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[] 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 }; - - AesKw kw = new AesKw192(); - - ICryptoTransform encryptor = null; - - try { - encryptor = kw.CreateEncryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] encrypted = null; - - try { - encrypted = encryptor.doFinal(CEK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - ICryptoTransform decryptor = null; - - try { - decryptor = kw.CreateDecryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] decrypted = null; - - try { - decrypted = decryptor.doFinal(EK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - - @Test - public void KeyVault_AesKw256() { - // Arrange - 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; - 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; - - AesKw kw = new AesKw256(); - - ICryptoTransform encryptor = null; - - try { - encryptor = kw.CreateEncryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] encrypted = null; - - try { - encrypted = encryptor.doFinal(CEK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - ICryptoTransform decryptor = null; - - try { - decryptor = kw.CreateDecryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); - } - - byte[] decrypted = null; - - try { - decrypted = decryptor.doFinal(EK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwDefaultProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java similarity index 60% rename from azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwDefaultProviderTest.java rename to azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java index a9b4495e9313a..d22e2107ce6ef 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwDefaultProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java @@ -21,15 +21,10 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; -import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; -import javax.crypto.BadPaddingException; import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -42,7 +37,10 @@ import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw192; import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw256; -public class AesKwDefaultProviderTest { +public class AesKwTest { + + // Always null for the default provider + private Provider _provider = null; private static boolean hasUnlimitedCrypto() { try { @@ -68,8 +66,9 @@ public void setUp() throws Exception { public void tearDown() throws Exception { } - // Always null for the default provider - private Provider _provider = null; + protected void setProvider(Provider provider) { + _provider = provider; + } @Test public void KeyVault_AesKw128() { @@ -84,28 +83,16 @@ public void KeyVault_AesKw128() { try { encryptor = kw.CreateEncryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); + } catch (Exception e) { + fail(e.getMessage()); } byte[] encrypted = null; try { encrypted = encryptor.doFinal(CEK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert @@ -115,28 +102,16 @@ public void KeyVault_AesKw128() { try { decryptor = kw.CreateDecryptor(KEK, _provider); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); + } catch (Exception e) { + fail(e.getMessage()); } byte[] decrypted = null; try { decrypted = decryptor.doFinal(EK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert @@ -161,17 +136,13 @@ public void KeyVault_AesKw192() { ICryptoTransform encryptor = null; try { - encryptor = kw.CreateEncryptor(KEK); + encryptor = kw.CreateEncryptor(KEK, _provider); if (!unlimited) fail("Expected InvalidKeyException"); } catch (InvalidKeyException e) { if (unlimited) fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); + } catch (Exception e) { + fail(e.getMessage()); } if (unlimited) { @@ -179,14 +150,8 @@ public void KeyVault_AesKw192() { try { encrypted = encryptor.doFinal(CEK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert @@ -196,16 +161,12 @@ public void KeyVault_AesKw192() { ICryptoTransform decryptor = null; try { - decryptor = kw.CreateDecryptor(KEK); + decryptor = kw.CreateDecryptor(KEK, _provider); if (!unlimited) fail("Expected InvalidKeyException"); } catch (InvalidKeyException e) { if (unlimited) fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); + } catch (Exception e) { + fail(e.getMessage()); } if (unlimited) { @@ -213,14 +174,8 @@ public void KeyVault_AesKw192() { try { decrypted = decryptor.doFinal(EK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert @@ -246,16 +201,12 @@ public void KeyVault_AesKw256() { ICryptoTransform encryptor = null; try { - encryptor = kw.CreateEncryptor(KEK); + encryptor = kw.CreateEncryptor(KEK, _provider); if (!unlimited) fail("Expected InvalidKeyException"); } catch (InvalidKeyException e) { if (unlimited) fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); + } catch (Exception e) { + fail(e.getMessage()); } if (unlimited) { @@ -263,14 +214,8 @@ public void KeyVault_AesKw256() { try { encrypted = encryptor.doFinal(CEK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert @@ -280,17 +225,13 @@ public void KeyVault_AesKw256() { ICryptoTransform decryptor = null; try { - decryptor = kw.CreateDecryptor(KEK); + decryptor = kw.CreateDecryptor(KEK, _provider); if (!unlimited) fail("Expected InvalidKeyException"); } catch (InvalidKeyException e) { if (unlimited) fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } catch (NoSuchPaddingException e) { - fail("NoSuchPaddingException"); - } catch (InvalidAlgorithmParameterException e) { - fail("InvalidAlgorithmParameterException"); + } catch (Exception e) { + fail(e.getMessage()); } if (unlimited) { @@ -298,14 +239,8 @@ public void KeyVault_AesKw256() { try { decrypted = decryptor.doFinal(EK); - } catch (IllegalBlockSizeException e) { - fail("IllegalBlockSizeException"); - } catch (BadPaddingException e) { - fail("BadPaddingException"); - } catch (InvalidKeyException e) { - fail("InvalidKeyException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); + } catch (Exception e) { + fail(e.getMessage()); } // Assert diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java new file mode 100644 index 0000000000000..c9a9c70acaeb3 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java @@ -0,0 +1,16 @@ +package com.microsoft.azure.keyvault.cryptography.test; + +import java.security.Provider; +import org.junit.Before; + +public class RsaKeyBCProviderTest extends RsaKeyTest { + + @Before + public void setUp() throws Exception { + try { + super.setProvider((Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance()); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + } +} diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java index e41ceaa460ab6..0d9fafb68ebbf 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -5,7 +5,7 @@ import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; -import java.security.KeyPairGenerator; +import java.security.Provider; import java.security.spec.KeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; @@ -24,6 +24,8 @@ import com.microsoft.azure.keyvault.cryptography.algorithms.RsaOaep; public class RsaKeyTest { + + private Provider _provider = null; @BeforeClass public static void setUpBeforeClass() throws Exception { @@ -40,6 +42,10 @@ public void setUp() throws Exception { @After public void tearDown() throws Exception { } + + protected void setProvider(Provider provider) { + _provider = provider; + } @Test public void testEncryptDecryptRsa15() throws Exception { @@ -179,24 +185,24 @@ public void testWrapUnwrapDefaultAlgorithm() throws Exception { assertArrayEquals(plaintext, decrypted); } - private static KeyPair getTestKeyMaterial() throws Exception { + private KeyPair getTestKeyMaterial() throws Exception { return getWellKnownKey(); } - private static KeyPair getWellKnownKey() throws Exception { - BigInteger modulus = new BigInteger("27266783713040163753473734334021230592631652450892850648620119914958066181400432364213298181846462385257448168605902438305568194683691563208578540343969522651422088760509452879461613852042845039552547834002168737350264189810815735922734447830725099163869215360401162450008673869707774119785881115044406101346450911054819448375712432746968301739007624952483347278954755460152795801894283389540036131881712321193750961817346255102052653789197325341350920441746054233522546543768770643593655942246891652634114922277138937273034902434321431672058220631825053788262810480543541597284376261438324665363067125951152574540779"); - BigInteger publicExponent = new BigInteger("65537"); + private 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"); + 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 publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent); KeySpec privateKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficient); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + KeyFactory keyFactory = _provider == null ? KeyFactory.getInstance("RSA") : KeyFactory.getInstance("RSA", _provider); return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java index ba86f68eeff90..a6a7936c9fa65 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java @@ -18,337 +18,17 @@ package com.microsoft.azure.keyvault.cryptography.test; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; import java.security.Provider; -import java.util.concurrent.ExecutionException; - -import org.apache.commons.lang3.tuple.Pair; -import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.azure.keyvault.cryptography.SymmetricKey; - -public class SymmetricKeyBCProviderTest { - - private Provider _provider = null; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - } +public class SymmetricKeyBCProviderTest extends SymmetricKeyBaseTest { @Before public void setUp() throws Exception { try { - _provider = (Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance(); - } catch (ClassNotFoundException ex) { - throw new RuntimeException(ex.getMessage()); - } catch (IllegalAccessException ex) { + super.setProvider((Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance()); + } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); - } catch (InstantiationException ex) { - throw new RuntimeException(ex.getMessage()); - } - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSymmetricKeyAesKw128() { - // Arrange - byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - 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[] 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 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); - - byte[] encrypted = null; - - try { - encrypted = key.wrapKeyAsync(CEK, "A128KW").get().getLeft(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, "A128KW").get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); } } - - @Test - public void testSymmetricKeyAesKw192() { - // Arrange - 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 }; - 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[] 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 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); - - byte[] encrypted = null; - - try { - encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyAesKw256() { - // Arrange - 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; - 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); - - byte[] encrypted = null; - - try { - encrypted = key.wrapKeyAsync(CEK, "A256KW").get().getLeft(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, "A256KW").get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyDefaultAlgorithmAesKw128() { - // Arrange - byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - 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[] 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 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); - - byte[] encrypted = null; - String algorithm = null; - - try { - Pair result = key.wrapKeyAsync(CEK, null).get(); - encrypted = result.getLeft(); - algorithm = result.getRight(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertEquals("A128KW", algorithm); - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, algorithm).get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyDefaultAlgorithmAesKw192() { - // Arrange - 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 }; - 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[] 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 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); - - byte[] encrypted = null; - String algorithm = null; - - try { - Pair result = key.wrapKeyAsync(CEK, null).get(); - encrypted = result.getLeft(); - algorithm = result.getRight(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertEquals( "A192KW", algorithm); - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, algorithm).get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyDefaultAlgorithmAesKw256() { - // Arrange - 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; - 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); - - byte[] encrypted = null; - String algorithm = null; - - try { - Pair result = key.wrapKeyAsync(CEK, null).get(); - encrypted = result.getLeft(); - algorithm = result.getRight(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertEquals("A256KW", algorithm); - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, algorithm).get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java new file mode 100644 index 0000000000000..36b6bf464aa16 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java @@ -0,0 +1,423 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.concurrent.ExecutionException; + +import javax.crypto.Cipher; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.azure.keyvault.cryptography.SymmetricKey; + +public abstract class SymmetricKeyBaseTest { + + private Provider _provider = null; + + private static boolean hasUnlimitedCrypto() { + try { + return Cipher.getMaxAllowedKeyLength("RC5") >= 256; + } catch (NoSuchAlgorithmException e) { + return false; + } + } + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public abstract void setUp() throws Exception; + + @After + public void tearDown() throws Exception { + } + + protected void setProvider(Provider provider) { + _provider = provider; + } + + @Test + public void testSymmetricKeyAesKw128() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + 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[] 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 }; + + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A128KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyAesKw192() { + // Arrange + 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 }; + 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[] 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 }; + + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyAesKw256() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A256KW").get().getLeft(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A256KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyDefaultAlgorithmAesKw128() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + 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[] 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 }; + + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + String algorithm = null; + + try { + Pair result = key.wrapKeyAsync(CEK, null).get(); + encrypted = result.getLeft(); + algorithm = result.getRight(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertEquals("A128KW", algorithm); + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, algorithm).get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyDefaultAlgorithmAesKw192() { + // Arrange + 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 }; + 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[] 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 }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + String algorithm = null; + + try { + Pair result = key.wrapKeyAsync(CEK, null).get(); + + encrypted = result.getLeft(); + algorithm = result.getRight(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertEquals( "A192KW", algorithm); + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, algorithm).get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyDefaultAlgorithmAesKw256() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + String algorithm = null; + + try { + Pair result = key.wrapKeyAsync(CEK, null).get(); + encrypted = result.getLeft(); + algorithm = result.getRight(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertEquals("A256KW", algorithm); + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, algorithm).get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + +} diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java index 9365b416988e3..384961ad2e643 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java @@ -18,407 +18,12 @@ package com.microsoft.azure.keyvault.cryptography.test; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.concurrent.ExecutionException; - -import javax.crypto.Cipher; - -import org.apache.commons.lang3.tuple.Pair; -import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.azure.keyvault.cryptography.SymmetricKey; -public class SymmetricKeyDefaultProviderTest { - - private static boolean hasUnlimitedCrypto() { - try { - return Cipher.getMaxAllowedKeyLength("RC5") >= 256; - } catch (NoSuchAlgorithmException e) { - return false; - } - } - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } +public class SymmetricKeyDefaultProviderTest extends SymmetricKeyBaseTest { @Before public void setUp() throws Exception { + super.setProvider(null); } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSymmetricKeyAesKw128() { - // Arrange - byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - 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[] 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 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK); - - byte[] encrypted = null; - - try { - encrypted = key.wrapKeyAsync(CEK, "A128KW").get().getLeft(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, "A128KW").get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyAesKw192() { - - // Arrange - 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 }; - 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[] 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 }; - - /* - * This test using the default JCE provider depends on whether unlimited security - * is installed or not. In the unlimited case, the full test should pass but in - * the limited case, it should fail with InvalidKeyException. - */ - boolean unlimited = hasUnlimitedCrypto(); - SymmetricKey key = new SymmetricKey("KEK", KEK); - - byte[] encrypted = null; - - try { - encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); - - if (!unlimited) fail("Expected ExecutionException"); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - - // In the limited case, the failure should be InvalidKeyException - // In the unlimited case, this should not fail - if (!unlimited) { - Throwable cause = e.getCause(); - if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); - } else { - fail("ExecutionException"); - } - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - if (unlimited) { - // Assert - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyAesKw256() { - // Arrange - 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; - 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; - - /* - * This test using the default JCE provider depends on whether unlimited security - * is installed or not. In the unlimited case, the full test should pass but in - * the limited case, it should fail with InvalidKeyException. - */ - boolean unlimited = hasUnlimitedCrypto(); - SymmetricKey key = new SymmetricKey("KEK", KEK); - - byte[] encrypted = null; - - try { - encrypted = key.wrapKeyAsync(CEK, "A256KW").get().getLeft(); - - if (!unlimited) fail("Expected ExecutionException"); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - // In the limited case, the failure should be InvalidKeyException - // In the unlimited case, this should not fail - if (!unlimited) { - Throwable cause = e.getCause(); - if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); - } else { - fail("ExecutionException"); - } - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - if (unlimited) { - // Assert - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, "A256KW").get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyDefaultAlgorithmAesKw128() { - // Arrange - byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - 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[] 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 }; - - SymmetricKey key = new SymmetricKey("KEK", KEK); - - byte[] encrypted = null; - String algorithm = null; - - try { - Pair result = key.wrapKeyAsync(CEK, null).get(); - encrypted = result.getLeft(); - algorithm = result.getRight(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertEquals("A128KW", algorithm); - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, algorithm).get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyDefaultAlgorithmAesKw192() { - // Arrange - 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 }; - 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[] 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 }; - - /* - * This test using the default JCE provider depends on whether unlimited security - * is installed or not. In the unlimited case, the full test should pass but in - * the limited case, it should fail with InvalidKeyException. - */ - boolean unlimited = hasUnlimitedCrypto(); - SymmetricKey key = new SymmetricKey("KEK", KEK); - - byte[] encrypted = null; - String algorithm = null; - - try { - Pair result = key.wrapKeyAsync(CEK, null).get(); - - encrypted = result.getLeft(); - algorithm = result.getRight(); - - if (!unlimited) fail("Expected ExecutionException"); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - // In the limited case, the failure should be InvalidKeyException - // In the unlimited case, this should not fail - if (!unlimited) { - Throwable cause = e.getCause(); - if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); - } else { - fail("ExecutionException"); - } - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - if (unlimited) { - // Assert - assertEquals( "A192KW", algorithm); - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, algorithm).get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - - @Test - public void testSymmetricKeyDefaultAlgorithmAesKw256() { - // Arrange - 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; - 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; - - /* - * This test using the default JCE provider depends on whether unlimited security - * is installed or not. In the unlimited case, the full test should pass but in - * the limited case, it should fail with InvalidKeyException. - */ - boolean unlimited = hasUnlimitedCrypto(); - SymmetricKey key = new SymmetricKey("KEK", KEK); - - byte[] encrypted = null; - String algorithm = null; - - try { - Pair result = key.wrapKeyAsync(CEK, null).get(); - encrypted = result.getLeft(); - algorithm = result.getRight(); - - if (!unlimited) fail("Expected ExecutionException"); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - // In the limited case, the failure should be InvalidKeyException - // In the unlimited case, this should not fail - if (!unlimited) { - Throwable cause = e.getCause(); - if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); - } else { - fail("ExecutionException"); - } - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - if (unlimited) { - // Assert - assertEquals("A256KW", algorithm); - assertArrayEquals(EK, encrypted); - - byte[] decrypted = null; - - try { - decrypted = key.unwrapKeyAsync(EK, algorithm).get(); - } catch (InterruptedException e) { - fail("InterrupedException"); - } catch (ExecutionException e) { - fail("ExecutionException"); - } catch (NoSuchAlgorithmException e) { - fail("NoSuchAlgorithmException"); - } - - // Assert - assertArrayEquals(CEK, decrypted); - } - - try { - key.close(); - } catch (IOException e) { - fail("Key could not be closed"); - } - } - } From 486ab38b7531229ac7f8b3e6b179a0a5f2e19263 Mon Sep 17 00:00:00 2001 From: Hervey Wilson Date: Fri, 19 Aug 2016 14:11:52 -0700 Subject: [PATCH 03/14] RS256 Signature support. --- .../microsoft/azure/keyvault/core/IKey.java | 2 +- azure-keyvault-cryptography/pom.xml | 10 + .../keyvault/cryptography/Algorithm.java | 2 +- .../cryptography/AlgorithmResolver.java | 30 +- .../azure/keyvault/cryptography/RsaKey.java | 106 ++++-- .../azure/keyvault/cryptography/Strings.java | 20 +- .../cryptography/algorithms/Rs256.java | 126 +++++++ .../cryptography/algorithms/RsaSignature.java | 215 +++++++++++ .../test/Base64UrlDeserializer.java | 43 +++ .../test/Base64UrlSerializer.java | 47 +++ .../cryptography/test/JsonWebKey.java | 346 ++++++++++++++++++ .../cryptography/test/JsonWebKeyType.java | 40 ++ .../cryptography/test/RsaKeyTest.java | 207 ++++------- .../keyvault/extensions/KeyVaultKey.java | 3 +- .../azure/keyvault/extensions/Strings.java | 8 +- 15 files changed, 1020 insertions(+), 185 deletions(-) create mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java create mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java create mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java diff --git a/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java index 264024d42b153..6cf69f7002aa9 100644 --- a/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java +++ b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java @@ -153,7 +153,7 @@ public interface IKey extends Closeable { * The signature to verify * @param algorithm * The algorithm to use, must be provided - * @return A ListenableFuture containing a boolean result + * @return A ListenableFuture containing the signature and the algorithm used. * @throws NoSuchAlgorithmException the algorithm is not valid */ ListenableFuture verifyAsync(final byte[] digest, final byte[] signature, final String algorithm) throws NoSuchAlgorithmException; diff --git a/azure-keyvault-cryptography/pom.xml b/azure-keyvault-cryptography/pom.xml index 17b3766ef8184..5b7688e30a0db 100644 --- a/azure-keyvault-cryptography/pom.xml +++ b/azure-keyvault-cryptography/pom.xml @@ -59,5 +59,15 @@ azure-keyvault-core ${project.version} + + com.fasterxml.jackson.core + jackson-databind + test + + + commons-codec + commons-codec + test + diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java index 810a6dfa4fb51..bfdcf9e54e790 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java @@ -23,7 +23,7 @@ public abstract class Algorithm { private final String _name; protected Algorithm(String name) { - if (Strings.isNullOrEmpty(name)) { + if (Strings.isNullOrWhiteSpace(name)) { throw new IllegalArgumentException("name"); } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java index 1eacaad75e0c3..c794b02867779 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java @@ -30,6 +30,7 @@ import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw128; import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw192; import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw256; +import com.microsoft.azure.keyvault.cryptography.algorithms.Rs256; import com.microsoft.azure.keyvault.cryptography.algorithms.Rsa15; import com.microsoft.azure.keyvault.cryptography.algorithms.RsaOaep; @@ -53,31 +54,38 @@ public class AlgorithmResolver { Default.put(Rsa15.AlgorithmName, new Rsa15()); Default.put(RsaOaep.AlgorithmName, new RsaOaep()); - // Default.put( Rs256.AlgorithmName, new Rs256() ); + Default.put( Rs256.AlgorithmName, new Rs256() ); // Default.put( RsNull.AlgorithmName, new RsNull() ); } private final ConcurrentMap _algorithms = new ConcurrentHashMap(); - /// - /// Returns the implementation for an algorithm name - /// - /// The algorithm name - /// + /** + * 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); } + /** + * Add/Update a named algorithm implementation. + * + * @param algorithmName The algorithm name. + * @param provider The implementation of the algorithm. + */ public void put(String algorithmName, Algorithm provider) { _algorithms.put(algorithmName, provider); } - /// - /// Removes an algorithm from the resolver - /// - /// The algorithm name + /** + * Remove a named algorithm implementation. + * + * @param algorithmName The algorithm name + */ public void remove(String algorithmName) { _algorithms.remove(algorithmName); } - } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java index b56511a99205d..4548a883c17fd 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java @@ -25,13 +25,13 @@ import java.security.Provider; import java.security.interfaces.RSAPublicKey; -import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.cryptography.algorithms.Rs256; import com.microsoft.azure.keyvault.cryptography.algorithms.RsaOaep; import com.microsoft.azure.keyvault.cryptography.Strings; @@ -44,28 +44,16 @@ public static int getDefaultKeySize() { return RsaKey.KeySize2048; } - private final String _kid; - private final KeyPair _keyPair; + private final String _kid; + private final KeyPair _keyPair; + private final Provider _provider; public RsaKey(String kid) throws NoSuchAlgorithmException { this(kid, getDefaultKeySize()); } public RsaKey(String kid, int keySize) throws NoSuchAlgorithmException { - this(kid, keySize, null); - /* - if (Strings.isNullOrWhiteSpace(kid)) { - throw new IllegalArgumentException("kid"); - } - - final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - - generator.initialize(keySize); - - _keyPair = generator.generateKeyPair(); - _kid = kid; - */ } public RsaKey(String kid, int keySize, Provider provider) throws NoSuchAlgorithmException { @@ -78,12 +66,16 @@ public RsaKey(String kid, int keySize, Provider provider) throws NoSuchAlgorithm generator.initialize(keySize); - _keyPair = generator.generateKeyPair(); - _kid = kid; - + _kid = kid; + _keyPair = generator.generateKeyPair(); + _provider = provider; } public RsaKey(String kid, KeyPair keyPair) { + this(kid, keyPair, null); + } + + public RsaKey(String kid, KeyPair keyPair, Provider provider) { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); @@ -96,9 +88,10 @@ public RsaKey(String kid, KeyPair keyPair) { if (keyPair.getPublic() == null || !(keyPair.getPublic() instanceof RSAPublicKey)) { throw new IllegalArgumentException("keyPair"); } - - _keyPair = keyPair; - _kid = kid; + + _kid = kid; + _keyPair = keyPair; + _provider = provider; } @Override @@ -113,8 +106,7 @@ public String getDefaultKeyWrapAlgorithm() { @Override public String getDefaultSignatureAlgorithm() { - // TODO: Signature Processing - return null; + return Rs256.AlgorithmName; } @Override @@ -146,7 +138,7 @@ public ListenableFuture decryptAsync(final byte[] ciphertext, final byte ListenableFuture result; try { - transform = algo.CreateDecryptor(_keyPair); + transform = algo.CreateDecryptor(_keyPair, _provider); result = Futures.immediateFuture(transform.doFinal(ciphertext)); } catch (Exception e) { result = Futures.immediateFailedFuture(e); @@ -176,7 +168,7 @@ public ListenableFuture> encryptAsync(final byte[ ListenableFuture> result; try { - transform = algo.CreateEncryptor(_keyPair); + transform = algo.CreateEncryptor(_keyPair, _provider); result = Futures.immediateFuture(Triple.of(transform.doFinal(plaintext), (byte[]) null, algorithmName)); } catch (Exception e) { result = Futures.immediateFailedFuture(e); @@ -206,7 +198,7 @@ public ListenableFuture> wrapKeyAsync(final byte[] key, fin ListenableFuture> result; try { - transform = algo.CreateEncryptor(_keyPair); + transform = algo.CreateEncryptor(_keyPair, _provider); result = Futures.immediateFuture(Pair.of(transform.doFinal(key), algorithmName)); } catch (Exception e) { result = Futures.immediateFailedFuture(e); @@ -240,7 +232,7 @@ public ListenableFuture unwrapKeyAsync(final byte[] encryptedKey, final ListenableFuture result; try { - transform = algo.CreateDecryptor(_keyPair); + transform = algo.CreateDecryptor(_keyPair, _provider); result = Futures.immediateFuture(transform.doFinal(encryptedKey)); } catch (Exception e) { result = Futures.immediateFailedFuture(e); @@ -250,13 +242,63 @@ public ListenableFuture unwrapKeyAsync(final byte[] encryptedKey, final } @Override - public ListenableFuture> signAsync(final byte[] digest, final String algorithm) { - return Futures.immediateFailedFuture(new NotImplementedException("signAsync is not currently supported")); + public ListenableFuture> signAsync(final byte[] digest, final String algorithm) throws NoSuchAlgorithmException { + + if (digest == null) { + throw new IllegalArgumentException("encryptedKey "); + } + + // Interpret the requested algorithm + if (Strings.isNullOrWhiteSpace(algorithm)) { + throw new IllegalArgumentException("algorithm"); + } + + // Interpret the requested algorithm + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + Rs256 algo = (Rs256)baseAlgorithm; + + Rs256.Rs256Signer signer = algo.createSigner(_keyPair); + + try { + return Futures.immediateFuture(Pair.of(signer.sign(digest), Rs256.AlgorithmName)); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } } @Override - public ListenableFuture verifyAsync(final byte[] digest, final byte[] signature, final String algorithm) { - return Futures.immediateFailedFuture(new NotImplementedException("verifyAsync is not currently supported")); + public ListenableFuture verifyAsync(final byte[] digest, final byte[] signature, final String algorithm) throws NoSuchAlgorithmException { + + if (digest == null) { + throw new IllegalArgumentException("encryptedKey "); + } + + // Interpret the requested algorithm + if (Strings.isNullOrWhiteSpace(algorithm)) { + throw new IllegalArgumentException("algorithm"); + } + + // Interpret the requested algorithm + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + Rs256 algo = (Rs256)baseAlgorithm; + + Rs256.Rs256Verifier signer = algo.createVerifier(_keyPair); + + try { + return Futures.immediateFuture(signer.verify(signature, digest)); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } } @Override diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java index c948e8e3453ab..c6cf7244a1532 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java @@ -18,19 +18,29 @@ package com.microsoft.azure.keyvault.cryptography; -import com.microsoft.azure.keyvault.cryptography.Strings; - -public class Strings { - +public final class Strings { + + /** + * Determines whether the parameter string is either null or empty. + * + * @param arg The string to be checked. + * @return true if the string is null or empty. + */ public static boolean isNullOrEmpty(String arg) { - if (arg == null || arg.isEmpty()) { + if (arg == null || arg.length() == 0) { return true; } return false; } + /** + * Determines whether the parameter string is null, empty or whitespace. + * + * @param arg The string to be checked. + * @return true if the string is null, empty or whitespace. + */ public static boolean isNullOrWhiteSpace(String arg) { if (Strings.isNullOrEmpty(arg) || arg.trim().isEmpty()) { diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java new file mode 100644 index 0000000000000..750a02f529ea7 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java @@ -0,0 +1,126 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.algorithms; + +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +/** + * + */ +public class Rs256 extends RsaSignature { + + static final String RsaNone = "RSA/ECB/PKCS1Padding"; + + public class Rs256Signer { + + private final KeyPair _keyPair; + private final int _emLen; + + private final BigInteger _n; + + Rs256Signer(KeyPair keyPair) { + + _keyPair = keyPair; + _n = ((RSAPublicKey)_keyPair.getPublic()).getModulus(); + + _emLen = getOctetLength( _n.bitLength() ); + } + + public byte[] sign(final byte[] digest) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + // Signing isn't just a case of encrypting the digest, there is much more to do. + // For details of the algorithm, see https://tools.ietf.org/html/rfc3447#section-8.2 + + // Construct the encoded message + byte[] EM = EMSA_PKCS1_V1_5_ENCODE(digest, _emLen, "SHA-256"); + + // Convert to integer message + BigInteger s = OS2IP(EM); + + // RSASP1(s) + s = RSASP1((RSAPrivateKey)_keyPair.getPrivate(), s); + + // Convert to octet sequence + return I2OSP(s, getOctetLength( _n.bitLength() ) ); + } + } + + public class Rs256Verifier { + + private final KeyPair _keyPair; + private final BigInteger _n; + private final int _emLength; + + Rs256Verifier(KeyPair keyPair) { + _keyPair = keyPair; + _n = ((RSAPublicKey)_keyPair.getPublic()).getModulus(); + _emLength = getOctetLength( _n.bitLength() ); + } + + public boolean verify(final byte[] signature, final byte[] digest) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + + if ( signature.length != getOctetLength( _n.bitLength() ) ) { + throw new IllegalBlockSizeException(); + } + + // Convert to integer signature + BigInteger s = OS2IP(signature); + + // Convert integer message + BigInteger m = RSAVP1((RSAPublicKey)_keyPair.getPublic(), s); + + + byte[] EM = I2OSP(m, getOctetLength( _n.bitLength() ) ); + byte[] EM2 = EMSA_PKCS1_V1_5_ENCODE(digest, _emLength, "SHA-256"); + + // TODO: Need constant time compare + if ( EM.length != EM2.length ) + return false; + + for ( int i = 0; i < digest.length; i++ ) { + if ( EM[i] != EM2[i] ) + return false; + } + + return true; + } + } + + public final static String AlgorithmName = "RS256"; + + public Rs256() { + super(AlgorithmName); + } + + public Rs256Signer createSigner(KeyPair keyPair) { + + return new Rs256Signer(keyPair); + } + + public Rs256Verifier createVerifier(KeyPair keyPair) { + return new Rs256Verifier(keyPair); + } +} diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java new file mode 100644 index 0000000000000..a9ac4d4559cbb --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java @@ -0,0 +1,215 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.algorithms; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; + +import com.microsoft.azure.keyvault.cryptography.AsymmetricSignatureAlgorithm; +import com.microsoft.azure.keyvault.cryptography.Strings; + +public abstract class RsaSignature extends AsymmetricSignatureAlgorithm { + + private static final BigInteger twoFiveSix = new BigInteger("256"); + private static final byte[] sha256Prefix = new byte[] { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 }; + + protected RsaSignature(String name) { + super(name); + } + + protected 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; + } + + 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); + } + + protected int getOctetLength(int bits) { + return ( bits % 8 > 0 ) ? bits >> 3 + 1 : bits >> 3; + } + + + /* + * See https://tools.ietf.org/html/rfc3447#section-4.2 + */ + protected BigInteger OS2IP(byte[] x) { + + if ( x == null || x.length == 0 ) { + throw new IllegalArgumentException("x"); + } + + return new BigInteger(1,x); + } + + /* + * See https://tools.ietf.org/html/rfc3447#section-4.1 + */ + protected byte[] I2OSP(BigInteger x, int xLen) { + + if ( x == null ) { + throw new IllegalArgumentException("x"); + } + + if ( xLen <= 0 ) { + throw new IllegalArgumentException("xLen"); + } + + if ( x.compareTo( twoFiveSix.pow(xLen) ) == 1 ) { + throw new IllegalArgumentException("integer too large"); + } + + byte[] bytes = x.toByteArray(); + + if ( bytes.length > xLen ) { + throw new IllegalArgumentException("integer too large"); + } + + byte[] result = new byte[xLen]; + + System.arraycopy(bytes, 0, result, xLen - bytes.length, bytes.length); + + return result; + } + + /* + * See https://tools.ietf.org/html/rfc3447#section-5.2.1 + */ + protected BigInteger RSASP1(RSAPrivateKey K, BigInteger m) { + + if ( K == null ) { + throw new IllegalArgumentException("K"); + } + + if ( m == null ) { + throw new IllegalArgumentException("m"); + } + + BigInteger n = K.getModulus(); + BigInteger d = K.getPrivateExponent(); + + if ( m.compareTo(BigInteger.ONE) == -1 || m.compareTo(n) != -1 ) { + throw new IllegalArgumentException("message representative out of range"); + } + + return m.modPow(d, n); + } + + /* + * See https://tools.ietf.org/html/rfc3447#section-5.2.2 + */ + protected BigInteger RSAVP1(RSAPublicKey K, BigInteger s) { + + if ( K == null ) { + throw new IllegalArgumentException("K"); + } + + if ( s == null ) { + throw new IllegalArgumentException("s"); + } + BigInteger n = K.getModulus(); + BigInteger e = K.getPublicExponent(); + + if ( s.compareTo(BigInteger.ONE) == -1 || s.compareTo(n) != -1 ) { + throw new IllegalArgumentException("message representative out of range"); + } + + return s.modPow(e, n); + } + + /* + * See https://tools.ietf.org/html/rfc3447#section-9.2 + */ + protected byte[] EMSA_PKCS1_V1_5_ENCODE(byte[] m, int emLen, String algorithm) throws NoSuchAlgorithmException { + + // Check m + if ( m == null || m.length == 0 ) { + throw new IllegalArgumentException("m"); + } + + byte[] algorithmPrefix = null; + MessageDigest messageDigest = null; + + // Check algorithm + if ( Strings.isNullOrWhiteSpace(algorithm) ) { + throw new IllegalArgumentException("algorithm"); + } + + // Only supported algorithms + if ( algorithm.equals("SHA-256") ) { + + // Initialize prefix and digest + algorithmPrefix = sha256Prefix; + messageDigest = MessageDigest.getInstance("SHA-256"); + } else { + throw new IllegalArgumentException("algorithm"); + } + + if ( algorithmPrefix == null || messageDigest == null ) { + throw new IllegalArgumentException("initialization with arguments failed"); + } + + // Hash the message + byte[] digest = messageDigest.digest(m); + + // Construct T, the DER encoded DigestInfo structure + byte[] T = new byte[algorithmPrefix.length + digest.length]; + + System.arraycopy(algorithmPrefix, 0, T, 0, algorithmPrefix.length); + System.arraycopy(digest, 0, T, algorithmPrefix.length, digest.length); + + if ( emLen < T.length + 11 ) { + throw new IllegalArgumentException("intended encoded message length too short"); + } + + // Construct PS + byte[] PS = new byte[emLen - T.length - 3]; + + for ( int i = 0; i < PS.length; i++ ) PS[i] = (byte) 0xff; + + // Construct EM + byte[] EM = new byte[PS.length + T.length + 3]; + + EM[0] = 0x00; EM[1] = 0x01; EM[PS.length + 2] = 0x00; + + System.arraycopy(PS, 0, EM, 2, PS.length); + System.arraycopy(T, 0, EM, PS.length + 3, T.length); + + return EM; + } + +} diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java new file mode 100644 index 0000000000000..8f54e8cdece21 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java @@ -0,0 +1,43 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import java.io.IOException; + +import org.apache.commons.codec.binary.Base64; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +public class Base64UrlDeserializer extends JsonDeserializer { + + static final Base64 _base64 = new Base64(-1, null, true); + + @Override + public byte[] deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + String text = jp.getText(); + if (text != null) { + return _base64.decode(text); + } + return null; + } + +} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java new file mode 100644 index 0000000000000..3cf15e392863d --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import java.io.IOException; + +import org.apache.commons.codec.binary.Base64; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +public class Base64UrlSerializer extends JsonSerializer { + + static final Base64 _base64 = new Base64(-1, null, true); + + @Override + public void serialize(byte[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + String text; + if (value == null) { + text = null; + } else if (value.length == 0) { + text = ""; + } else { + text = _base64.encodeAsString(value); + } + jgen.writeString(text); + } + +} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java new file mode 100644 index 0000000000000..ec65f0d6fea55 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java @@ -0,0 +1,346 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.PublicKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.security.spec.RSAPrivateKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY, setterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) +public class JsonWebKey { + + private String kid; + + @JsonProperty("kid") + public String getKid() { + return kid; + } + + public void setKid(String kid) { + this.kid = kid; + } + + private String kty; + + @JsonProperty("kty") + public String getKty() { + return kty; + } + + public void setKty(String kty) { + this.kty = kty; + } + + private String[] keyOps; + + @JsonProperty("key_ops") + public String[] getKeyOps() { + return keyOps; + } + + public void setKeyOps(String[] keyOps) { + this.keyOps = keyOps; + } + + private byte[] n; + + @JsonProperty("n") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getN() { + return n; + } + + public void setN(byte[] n) { + this.n = n; + } + + private byte[] e; + + @JsonProperty("e") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getE() { + return e; + } + + public void setE(byte[] e) { + this.e = e; + } + + private byte[] d; + + @JsonProperty("d") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getD() { + return d; + } + + public void setD(byte[] d) { + this.d = d; + } + + private byte[] dp; + + @JsonProperty("dp") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getDP() { + return dp; + } + + public void setDP(byte[] dp) { + this.dp = dp; + } + + private byte[] dq; + + @JsonProperty("dq") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getDQ() { + return dq; + } + + public void setDQ(byte[] dq) { + this.dq = dq; + } + + private byte[] qi; + + @JsonProperty("qi") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getQI() { + return qi; + } + + public void setQI(byte[] qi) { + this.qi = qi; + } + + private byte[] p; + + @JsonProperty("p") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getP() { + return p; + } + + public void setP(byte[] p) { + this.p = p; + } + + private byte[] q; + + @JsonProperty("q") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getQ() { + return q; + } + + public void setQ(byte[] q) { + this.q = q; + } + + private byte[] k; + + @JsonProperty("k") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getk() { + return k; + } + + public void setK(byte[] k) { + this.k = k; + } + + private byte[] t; + + @JsonProperty("key_hsm") + @JsonSerialize(using = Base64UrlSerializer.class) + @JsonDeserialize(using = Base64UrlDeserializer.class) + public byte[] getT() { + return t; + } + + public void setT(byte[] t) { + this.t = t; + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + private RSAPublicKeySpec getRSAPublicKeySpec() { + + return new RSAPublicKeySpec(toBigInteger(n), toBigInteger(e)); + } + + private RSAPrivateKeySpec getRSAPrivateKeySpec() { + + return new RSAPrivateCrtKeySpec(toBigInteger(n), toBigInteger(e), toBigInteger(d), toBigInteger(p), toBigInteger(q), toBigInteger(dp), toBigInteger(dq), toBigInteger(qi)); + } + + 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 new IllegalStateException(e); + } + } + + 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 new IllegalStateException(e); + } + } + + private void checkRSACompatible() { + if (!JsonWebKeyType.RSA.equals(kty) && !JsonWebKeyType.RSAHSM.equals(kty)) { + throw 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); + } + + public static JsonWebKey fromRSA(KeyPair keyPair) { + + RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate(); + JsonWebKey key = null; + + if (privateKey != null) { + + key = new JsonWebKey(); + + key.setKty(JsonWebKeyType.RSA); + + key.setN(toByteArray(privateKey.getModulus())); + key.setE(toByteArray(privateKey.getPublicExponent())); + key.setD(toByteArray(privateKey.getPrivateExponent())); + key.setP(toByteArray(privateKey.getPrimeP())); + key.setQ(toByteArray(privateKey.getPrimeQ())); + key.setDP(toByteArray(privateKey.getPrimeExponentP())); + key.setDQ(toByteArray(privateKey.getPrimeExponentQ())); + key.setQI(toByteArray(privateKey.getCrtCoefficient())); + } else { + + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + + key = new JsonWebKey(); + + key.setKty(JsonWebKeyType.RSA); + + key.setN(toByteArray(publicKey.getModulus())); + key.setE(toByteArray(publicKey.getPublicExponent())); + key.setD(null); + key.setP(null); + key.setQ(null); + key.setDP(null); + key.setDQ(null); + key.setQI(null); + } + + return key; + } + + public KeyPair toRSA() { + return this.toRSA(false); + } + + public KeyPair toRSA(boolean includePrivateParameters) { + + return toRSA(includePrivateParameters, null); + } + + 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); + } + } +} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java new file mode 100644 index 0000000000000..f3b1760652637 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java @@ -0,0 +1,40 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Supported JsonWebKey key types (kty) + */ +public final class JsonWebKeyType { + + public static final String EC = "EC"; + public static final String RSA = "RSA"; + public static final String RSAHSM = "RSA-HSM"; + public static final String OCT = "oct"; + + public static final List ALL_TYPES = Collections.unmodifiableList(Arrays.asList(new String[] { EC, RSA, RSAHSM, OCT })); + + private JsonWebKeyType() { + // not instantiable + } +} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java index 0d9fafb68ebbf..7c9b29b956bd5 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -2,15 +2,10 @@ import static org.junit.Assert.*; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.KeyPair; +import java.security.MessageDigest; import java.security.Provider; -import java.security.spec.KeySpec; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.util.concurrent.Future; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.junit.After; @@ -19,12 +14,19 @@ import org.junit.BeforeClass; import org.junit.Test; +import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.cryptography.RsaKey; +import com.microsoft.azure.keyvault.cryptography.algorithms.Rs256; import com.microsoft.azure.keyvault.cryptography.algorithms.Rsa15; import com.microsoft.azure.keyvault.cryptography.algorithms.RsaOaep; public class RsaKeyTest { + // A Content Encryption Key, or Message. This value is kept consistent with the .NET + // unit test cases to enable cross platform testing. + static final byte[] CEK = { 4, (byte) 211, 31, (byte) 197, 84, (byte) 157, (byte) 252, (byte) 254, 11, 100, (byte) 157, (byte) 250, 63, (byte) 170, 106, (byte) 206, 107, 124, (byte) 212, 45, 111, 107, 9, (byte) 219, (byte) 200, (byte) 177, 0, (byte) 240, (byte) 143, (byte) 156, 44, (byte) 207 }; + static final String CrossPlatformSignature = "RaNc+8WcWxplS8I7ynJLSoLJKz+dgBvrZhIGH3VFlTTyzu7b9d+lpaV9IKhzCNBsgSysKhgL7EZwVCOTBZ4m6xvKSXqVFXYaBPyBTD7VoKPMYMW6ai5x6xV5XAMaZPfMkff3Deg/RXcc8xQ28FhYuUa8yly01GySY4Hk55anEvb2wBxSy1UGun/0LE1lYH3C3XEgSry4cEkJHDJl1hp+wB4J/noXOqn5ECGU+/4ehBJOyW1gtUH0/gRe8yXnDH0AXepHRyH8iBHLWlKX1r+1/OrMulqOoi82RZzJlTyEz9X+bsQhllqGF6n3hdLS6toH9o7wUtwYNqSx82JuQT6iMg=="; + private Provider _provider = null; @BeforeClass @@ -48,163 +50,110 @@ protected void setProvider(Provider provider) { } @Test - public void testEncryptDecryptRsa15() throws Exception { + public void testRsa15() throws Exception { - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); + RsaKey key = getTestRsaKey(); - // Encrypt the plaintext - Triple result = key.encryptAsync(plaintext, null, null, Rsa15.AlgorithmName).get(); - - byte[] ciphertext = result.getLeft(); + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, Rsa15.AlgorithmName).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); - assertEquals(Rsa15.AlgorithmName, result.getRight()); - - // Decrypt the ciphertext - Future decryptResult = key.decryptAsync(ciphertext, null, null, null, result.getRight()); - byte[] decrypted = decryptResult.get(); - - key.close(); - - assertArrayEquals(plaintext, decrypted); - } - - @Test - public void testEncryptDecryptRsaOaep() throws Exception { - - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); + // Assert + assertEquals(Rsa15.AlgorithmName, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); - // Encrypt the plaintext - Triple result = key.encryptAsync(plaintext, null, null, RsaOaep.AlgorithmName).get(); + // Encrypt and Decrypt + Triple encrypted = key.encryptAsync(CEK, null, null, Rsa15.AlgorithmName).get(); + byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get(); - byte[] ciphertext = result.getLeft(); - - assertEquals(RsaOaep.AlgorithmName, result.getRight()); - - // Decrypt the ciphertext - Future decryptResult = key.decryptAsync(ciphertext, null, null, null, result.getRight()); - byte[] decrypted = decryptResult.get(); + // Assert + assertEquals(Rsa15.AlgorithmName, encrypted.getRight()); + assertArrayEquals(CEK, decrypted); key.close(); - - assertArrayEquals(plaintext, decrypted); } @Test - public void testWrapUnwrapRsa15() throws Exception { + public void testRsaOaep() throws Exception { - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); + RsaKey key = getTestRsaKey(); - // Encrypt the plaintext - Pair result = key.wrapKeyAsync(plaintext, Rsa15.AlgorithmName).get(); + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, RsaOaep.AlgorithmName).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); - byte[] ciphertext = result.getLeft(); - - assertEquals(Rsa15.AlgorithmName, result.getRight()); - - // Decrypt the ciphertext - Future decryptResult = key.unwrapKeyAsync(ciphertext, result.getRight()); - byte[] decrypted = decryptResult.get(); - - key.close(); - - assertArrayEquals(plaintext, decrypted); - } + // Assert + assertEquals(RsaOaep.AlgorithmName, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); - @Test - public void testWrapUnwrapRsaOaep() throws Exception { - - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); - - // Encrypt the plaintext - Pair result = key.wrapKeyAsync(plaintext, RsaOaep.AlgorithmName).get(); + // Encrypt and Decrypt + Triple encrypted = key.encryptAsync(CEK, null, null, RsaOaep.AlgorithmName).get(); + byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get(); - byte[] ciphertext = result.getLeft(); - - assertEquals(RsaOaep.AlgorithmName, result.getRight()); - - // Decrypt the ciphertext - Future decryptResult = key.unwrapKeyAsync(ciphertext, result.getRight()); - byte[] decrypted = decryptResult.get(); + // Assert + assertEquals(RsaOaep.AlgorithmName, encrypted.getRight()); + assertArrayEquals(CEK, decrypted); key.close(); - - assertArrayEquals(plaintext, decrypted); } @Test - public void testEncryptDecryptDefaultAlgorithm() throws Exception { + public void testDefaultAlgorithm() throws Exception { - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); + RsaKey key = getTestRsaKey(); - // Encrypt the plaintext - Triple result = key.encryptAsync(plaintext, null, null, null).get(); - - byte[] ciphertext = result.getLeft(); + assertEquals(RsaOaep.AlgorithmName, key.getDefaultEncryptionAlgorithm()); + assertEquals(RsaOaep.AlgorithmName, key.getDefaultKeyWrapAlgorithm()); + assertEquals(Rs256.AlgorithmName, key.getDefaultSignatureAlgorithm()); + + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, key.getDefaultKeyWrapAlgorithm()).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); - assertEquals(RsaOaep.AlgorithmName, result.getRight()); + // Assert + assertEquals(RsaOaep.AlgorithmName, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); - // Decrypt the ciphertext - Future decryptResult = key.decryptAsync(ciphertext, null, null, null, result.getRight()); - byte[] decrypted = decryptResult.get(); + // Encrypt and Decrypt + Triple encrypted = key.encryptAsync(CEK, null, null, key.getDefaultEncryptionAlgorithm()).get(); + byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get(); + + // Assert + assertEquals(RsaOaep.AlgorithmName, encrypted.getRight()); + assertArrayEquals(CEK, decrypted); key.close(); - - assertArrayEquals(plaintext, decrypted); } - + @Test - public void testWrapUnwrapDefaultAlgorithm() throws Exception { + public void testSignVerify() throws Exception { + + RsaKey key = getTestRsaKey(); - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(CEK); + + Pair signature = key.signAsync(hash, "RS256").get(); + boolean result = key.verifyAsync(hash, signature.getLeft(), "RS256").get(); - // Encrypt the plaintext - Pair result = key.wrapKeyAsync(plaintext, null).get(); - - byte[] ciphertext = result.getLeft(); + assertTrue(result); - assertEquals(RsaOaep.AlgorithmName, result.getRight()); + // Now prove we can verify the cross platform signature + result = key.verifyAsync(hash, Base64.decodeBase64(CrossPlatformSignature), "RS256").get(); - // Decrypt the ciphertext - Future decryptResult = key.unwrapKeyAsync(ciphertext, result.getRight()); - byte[] decrypted = decryptResult.get(); + assertTrue(result); key.close(); - - assertArrayEquals(plaintext, decrypted); } - - private KeyPair getTestKeyMaterial() throws Exception { - - return getWellKnownKey(); - } - - private 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 = _provider == null ? KeyFactory.getInstance("RSA") : KeyFactory.getInstance("RSA", _provider); - - return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); + + private RsaKey getTestRsaKey() throws Exception { + String jwkString = "{\"kty\":\"RSA\",\"n\":\"rZ8pnmXkhfmmgNWVVdtNcYy2q0OAcCGIpeFzsN9URqJsiBEiWQfxlUxFTbM4kVWPqjauKt6byvApBGEeMA7Qs8kxwRVP-BD4orXRe9VPgliM92rH0UxQWHmCHUe7G7uUAFPwbiDVhWuFzELxNa6Kljg6Z9DuUKoddmQvlYWj8uSunofCtDi_zzlZKGYTOYJma5IYScHNww1yjLp8-b-Be2UdHbrPkCv6Nuwi6MVIKjPpEeRQgfefRmxDBJQKY3OfydMXZmEwukYXVkUcdIP8XwG2OxnfdRK0oAo0NDebNNVuT89k_3AyZLTr1KbDmx1nnjwa8uB8k-uLtcOC9igbTw\",\"e\":\"AQAB\",\"d\":\"H-z7hy_vVJ9yeZBMtIvt8qpQUK_J51STPwV085otcgud72tPKJXoW2658664ASl9kGwbnLBwb2G3-SEunuGqiNS_PGUB3niob6sFSUMRKsPDsB9HfPoOcCZvwZiWFGRqs6C7vlR1TuJVqRjKJ_ffbf4K51oo6FZPspx7j4AShLAwLUSQ60Ld5QPuxYMYZIMpdVbMVIVHJ26pR4Y18e_0GYmEGnbF5N0HkwqQmfmTiIK5aoGnD3GGgqHeHmWBwh6_WAq90ITLcX_zBeqQUgBSj-Z5v61SroO9Eang36T9mMoYrcPpYwemtAOb4HhQYDj8dCCfbeOcVmvZ9UJKWCX2oQ\",\"dp\":\"HW87UpwPoj3lPI9B9K1hJFeuGgarpakvtHuk1HpZ5hXWFGAJiXoWRV-jvYyjoM2k7RpSxPyuuFFmYHcIxiGFp2ES4HnP0BIhKVa2DyugUxIEcMK53C43Ub4mboJPZTSC3sapKgAmA2ue624sapWmshTPpx9qnUP2Oj3cSMkgMGE\",\"dq\":\"RhwEwb5FYio0GS2tmul8FAYsNH7JDehwI1yUApnTiakhSenFetml4PYyVkKR4csgLZEi3RY6J3R8Tg-36zrZuF7hxhVJn80L5_KETSpfEI3jcrXMVg4SRaMsWLY9Ahxflt2FJgUnHOmWRLmP6_hmaTcxxSACjbyUd_HhwNavD5E\",\"qi\":\"wYPZ4lKIslA1w3FaAzQifnNLABYXXUZ_KAA3a8T8fuxkdE4OP3xIFX7WHhnmBd6uOFiEcGoeq2jNQqDg91rV5661-5muQKcvp4uUsNId5rQw9EZw-kdDcwMtVFTEBfvVuyp83X974xYAHn1Jd8wWohSwrpi1QuH5cQMR5Fm6I1A\",\"p\":\"74Ot7MgxRu4euB31UWnGtrqYPjJmvbjYESS43jfDfo-s62ggV5a39P_YPg6oosgtGHNw0QDxunUOXNu9iriaYPf_imptRk69bKN8Nrl727Y-AaBYdLf1UZuwz8X07FqHAH5ghYpk79djld8QvkUUJLpx6rzcW8BJLTOi46DtzZE\",\"q\":\"uZJu-qenARIt28oj_Jlsk-p_KLnqdczczZfbRDd7XNp6csGLa8R0EyYqUB4xLWELQZsX4tAu9SaAO62tuuEy5wbOAmOVrq2ntoia1mGQSJdoeVq6OqtN300xVnaBc3us0rm8C6-824fEQ1PWXoulXLKcSqBhFT-hQahsYi-kat8\"}"; + ObjectMapper mapper = new ObjectMapper(); + JsonWebKey jwk = null; + + jwk = mapper.readValue(jwkString, JsonWebKey.class); + + return new RsaKey("foo", jwk.toRSA(true, _provider) ); } } diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java index 485fa3a0b797f..c33fb8eefbabe 100644 --- a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java @@ -29,10 +29,9 @@ import com.microsoft.azure.keyvault.KeyVaultClient; import com.microsoft.azure.keyvault.core.IKey; import com.microsoft.azure.keyvault.cryptography.RsaKey; -import com.microsoft.azure.keyvault.cryptography.Strings; +import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyOperationResult; -import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; import com.microsoft.rest.ServiceResponse; diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java index 3b4d8ad3b1afb..52ef356b78e3b 100644 --- a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java @@ -24,13 +24,13 @@ public class Strings { /** - * Verifier if the string is empty or null. + * Determines whether the parameter string is either null or empty. * @param arg the string to verify - * @return true if the string is empty or null and false otherwise + * @return true if the string is empty or null and false otherwise. */ public static boolean isNullOrEmpty(String arg) { - if (arg == null || arg.isEmpty()) { + if (arg == null || arg.length() == 0) { return true; } @@ -38,7 +38,7 @@ public static boolean isNullOrEmpty(String arg) { } /** - * Verifier if the string is empty, contains only whitespace or is null. + * Determines whether the parameter string is null, empty or whitespace. * @param arg the string to verify * @return true if the string is empty, contains only whitespace or is null and false otherwise */ From 32d227336c1a4fe2ed07db7ac124cc2c4501282c Mon Sep 17 00:00:00 2001 From: Pooneh Date: Mon, 22 Aug 2016 09:38:56 -0700 Subject: [PATCH 04/14] Adding managed field for certifciates and use base class of attributes in request classes. --- .../azure/keyvault/models/KeyBundle.java | 25 +++++++++++++++++ .../azure/keyvault/models/KeyItem.java | 25 +++++++++++++++++ .../azure/keyvault/models/SecretBundle.java | 25 +++++++++++++++++ .../azure/keyvault/models/SecretItem.java | 25 +++++++++++++++++ .../requests/CreateCertificateRequest.java | 5 ++-- .../keyvault/requests/CreateKeyRequest.java | 5 ++-- .../requests/ImportCertificateRequest.java | 5 ++-- .../keyvault/requests/ImportKeyRequest.java | 5 ++-- .../requests/MergeCertificateRequest.java | 5 ++-- .../keyvault/requests/SetSecretRequest.java | 5 ++-- .../requests/UpdateCertificateRequest.java | 6 ++--- .../keyvault/requests/UpdateKeyRequest.java | 5 ++-- .../requests/UpdateSecretRequest.java | 5 ++-- .../test/CertificateOperationsTest.java | 27 +++++++++++++------ .../keyvault/test/KeyOperationsTest.java | 9 ++++--- .../keyvault/test/SecretOperationsTest.java | 8 ++++-- 16 files changed, 158 insertions(+), 32 deletions(-) diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java index 453e5177fab2b..ae4a62b7cbacc 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java @@ -38,6 +38,11 @@ public class KeyBundle { */ private Map tags; + /** + * True if the secret's lifetime is managed by key vault. + */ + private Boolean managed; + /** * Get the key value. * @@ -98,6 +103,26 @@ public KeyBundle withTags(Map tags) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * Set the managed value. + * + * @param managed the managed value to set + * @return the KeyBundle object itself. + */ + public KeyBundle withManaged(Boolean managed) { + this.managed = managed; + return this; + } + /** * The key identifier. * @return identifier for the key diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java index 05584de30f1ac..4dea299b81d8c 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java @@ -33,6 +33,11 @@ public class KeyItem { */ private Map tags; + /** + * True if the secret's lifetime is managed by key vault. + */ + private Boolean managed; + /** * Get the kid value. * @@ -93,6 +98,26 @@ public KeyItem withTags(Map tags) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * Set the managed value. + * + * @param managed the managed value to set + * @return the KeyItem object itself. + */ + public KeyItem withManaged(Boolean managed) { + this.managed = managed; + return this; + } + /** * The key identifier. * @return The Identifier value diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java index c52baf76b82f9..6dea046e03cc5 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java @@ -53,6 +53,11 @@ public class SecretBundle { */ private String kid; + /** + * True if the secret's lifetime is managed by key vault. + */ + private Boolean managed; + /** * Get the value value. * @@ -173,6 +178,26 @@ public SecretBundle withKid(String kid) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * Set the managed value. + * + * @param managed the managed value to set + * @return the SecretBundle object itself. + */ + public SecretBundle withManaged(Boolean managed) { + this.managed = managed; + return this; + } + /** * the secret identifier. * @return The Identifier value diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java index 5359f9cba67ca..db383c7f7f0fb 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java @@ -38,6 +38,11 @@ public class SecretItem { */ private String contentType; + /** + * True if the secret's lifetime is managed by key vault. + */ + private Boolean managed; + /** * Get the id value. * @@ -118,6 +123,26 @@ public SecretItem withContentType(String contentType) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * Set the managed value. + * + * @param managed the managed value to set + * @return the SecretItem object itself. + */ + public SecretItem withManaged(Boolean managed) { + this.managed = managed; + return this; + } + /** * the secret identifier. * @return The Identifier value diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java index fb9a8e5db704b..84900c5ae2143 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.CertificateAttributes; import com.microsoft.azure.keyvault.models.CertificatePolicy; import com.microsoft.azure.keyvault.models.IssuerReference; @@ -69,8 +70,8 @@ public Builder withPolicy(CertificatePolicy certificatePolicy) { * The attributes of the certificate. * @return the Builder object itself. */ - public Builder withAttributes(CertificateAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java index 96f416bb9cf36..e197baa16c33b 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.KeyAttributes; /** @@ -84,8 +85,8 @@ public Builder withKeyOperations(List keyOperations) { * the key management attributes value to set. * @return the Builder object itself. */ - public Builder withAttributes(KeyAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (KeyAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java index 56f04bd98a454..431c595ca9709 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.CertificateAttributes; import com.microsoft.azure.keyvault.models.CertificatePolicy; import com.microsoft.azure.keyvault.models.IssuerReference; @@ -89,8 +90,8 @@ public Builder withPolicy(CertificatePolicy policy) { * The attributes of the certificate. * @return the Builder object itself. */ - public Builder withAttributes(CertificateAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java index 8fb02162ff3da..b644554936253 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyAttributes; @@ -71,8 +72,8 @@ public Builder withHsm(boolean isHsm) { * the key management attributes value to set * @return the Builder object itself. */ - public Builder withAttributes(KeyAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (KeyAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java index 9ad223c6a4816..1a1569e41d97c 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.CertificateAttributes; /** @@ -54,8 +55,8 @@ public Builder(String vaultBaseUrl, String certificateName, List x509Cer * The attributes of the certificate. * @return the Builder object itself. */ - public Builder withAttributes(CertificateAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java index a34c08d296f73..2bfa1cc3c6bc4 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java @@ -3,6 +3,7 @@ import java.util.Collections; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.SecretAttributes; /** @@ -66,8 +67,8 @@ public Builder withContentType(String contentType) { * The secret management attributes. * @return the Builder object itself. */ - public Builder withAttributes(SecretAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (SecretAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java index 407b4c1407d27..b1403613b462d 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.Map; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.CertificateAttributes; import com.microsoft.azure.keyvault.models.CertificatePolicy; import com.microsoft.azure.keyvault.models.IssuerReference; @@ -11,7 +12,6 @@ import com.microsoft.azure.keyvault.models.LifetimeAction; import com.microsoft.azure.keyvault.models.SecretProperties; import com.microsoft.azure.keyvault.models.X509CertificateProperties; -import com.microsoft.azure.keyvault.requests.CreateCertificateRequest.Builder; /** * The update certificate request class. @@ -84,8 +84,8 @@ public Builder withPolicy(CertificatePolicy certificatePolicy) { * The attributes of the certificate. * @return the Builder object itself. */ - public Builder withAttributes(CertificateAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java index d87b8c798c583..bad0b37d43b75 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java @@ -6,6 +6,7 @@ import java.util.Map; import com.microsoft.azure.keyvault.KeyIdentifier; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.KeyAttributes; /** @@ -94,8 +95,8 @@ public Builder withKeyOperations(List keyOperations) { * the key management attributes value to set * @return the Builder object itself. */ - public Builder withAttributes(KeyAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (KeyAttributes) attributes; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java index 732aa8843ae33..e56f9f7713e28 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java @@ -4,6 +4,7 @@ import java.util.Map; import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.SecretAttributes; /** @@ -89,8 +90,8 @@ public Builder withContentType(String contentType) { * The secret management attributes. * @return the Builder object itself. */ - public Builder withAttributes(SecretAttributes attributes) { - this.attributes = attributes; + public Builder withAttributes(Attributes attributes) { + this.attributes = (SecretAttributes) attributes; return this; } diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java index 85839d816a2aa..18a13e9423e9b 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -57,8 +57,10 @@ import com.microsoft.azure.PagedList; import com.microsoft.azure.keyvault.CertificateIdentifier; +import com.microsoft.azure.keyvault.KeyIdentifier; import com.microsoft.azure.keyvault.SecretIdentifier; import com.microsoft.azure.keyvault.models.AdministratorDetails; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.CertificateAttributes; import com.microsoft.azure.keyvault.models.CertificateBundle; import com.microsoft.azure.keyvault.models.Contact; @@ -66,6 +68,7 @@ import com.microsoft.azure.keyvault.models.IssuerBundle; import com.microsoft.azure.keyvault.models.IssuerCredentials; import com.microsoft.azure.keyvault.models.IssuerReference; +import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyVaultErrorException; import com.microsoft.azure.keyvault.models.OrganizationDetails; import com.microsoft.azure.keyvault.models.CertificateItem; @@ -143,8 +146,8 @@ public void createSelfSignedCertificatePkcs12() throws Exception { .withIssuerReference(issuerReference) .withX509CertificateProperties(x509Properties); - CertificateAttributes attribute = (CertificateAttributes) new CertificateAttributes() - .withEnabled(false) + Attributes attribute = new CertificateAttributes() + .withEnabled(true) .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); @@ -177,7 +180,13 @@ public void createSelfSignedCertificatePkcs12() throws Exception { // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + Assert.assertTrue(secret.managed()); + // Retrieve the key backing the certificate + KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier(); + KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier()).getBody(); + Assert.assertTrue(keyBundle.managed()); + // Load the secret into a KeyStore String secretPassword = ""; KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); @@ -325,7 +334,8 @@ public void createCertificatePkcs12() throws Exception { // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - + Assert.assertTrue(secret.managed()); + // Load the secret into a KeyStore String secretPassword = ""; KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); @@ -538,7 +548,7 @@ public void importCertificatePkcs12() throws Exception { // Set content type to indicate the certificate is PKCS12 format. SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12); CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties); - CertificateAttributes attribute = (CertificateAttributes) new CertificateAttributes().withEnabled(true); + Attributes attribute = new CertificateAttributes().withEnabled(true); String vaultUri = getVaultUri(); String certificateName = "importCertPkcs"; @@ -565,7 +575,8 @@ public void importCertificatePkcs12() throws Exception { // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); - + Assert.assertTrue(secret.managed()); + // Load the secret into a KeyStore String secretPassword = ""; KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); @@ -605,14 +616,13 @@ public void certificateUpdate() throws Exception { .build()).getBody(); - CertificateAttributes attribute = (CertificateAttributes) new CertificateAttributes() - .withEnabled(false) + Attributes attribute = new CertificateAttributes() .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); CertificateBundle updatedCertBundle = keyVaultClient.updateCertificate( new UpdateCertificateRequest .Builder(vaultUri, certificateName) - .withAttributes((CertificateAttributes) attribute.withEnabled(false)) + .withAttributes(attribute.withEnabled(false)) .withTags(sTags) .build()).getBody(); Assert.assertEquals(attribute.enabled(), updatedCertBundle.attributes().enabled()); @@ -1098,6 +1108,7 @@ private void validatePem(CertificateBundle certificateBundle, String subjectName // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + Assert.assertTrue(secret.managed()); String secretValue = secret.value(); // Extract private key from PEM diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java index f227d9f5ca3cb..c4fd3b4d6209f 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -47,6 +47,7 @@ import com.microsoft.azure.keyvault.requests.CreateKeyRequest; import com.microsoft.azure.keyvault.requests.ImportKeyRequest; import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyAttributes; import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; @@ -68,7 +69,7 @@ public void transparentAuthentication() throws Exception { Map tags = new HashMap(); tags.put("foo", "baz"); List keyOps = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); - KeyAttributes attribute = (KeyAttributes) new KeyAttributes() + Attributes attribute = new KeyAttributes() .withEnabled(true) .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); @@ -108,7 +109,7 @@ public void importKeyOperation() throws Exception { } private void checkImportOperation(KeyBundle keyBundle, boolean importToHardware) throws Exception { - KeyAttributes attribute = (KeyAttributes) new KeyAttributes() + Attributes attribute = new KeyAttributes() .withEnabled(true) .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); @@ -546,7 +547,7 @@ private static KeyPair getWellKnownKey() throws Exception { return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); } - private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, String kty, List key_ops, KeyAttributes attributes) throws Exception { + private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, String kty, List key_ops, Attributes attributes) throws Exception { String prefix = vault + "/keys/" + keyName + "/"; String kid = bundle.key().kid(); Assert.assertTrue( @@ -562,6 +563,8 @@ private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String Assert.assertNotNull("\"updated\" should not be null.", bundle.attributes().updated()); compareAttributes(attributes, bundle.attributes()); + + Assert.assertTrue(bundle.managed() == null || bundle.managed() == false); } diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java index 7378e9ebc9bee..1673ded8ff130 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java @@ -25,6 +25,7 @@ import org.junit.Assert; import org.junit.Test; +import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.KeyVaultErrorException; import com.microsoft.azure.keyvault.models.SecretAttributes; import com.microsoft.azure.keyvault.models.SecretBundle; @@ -46,7 +47,7 @@ public void transparentAuthentication() throws Exception { // Create a secret on a vault. { - SecretAttributes attributes = (SecretAttributes) new SecretAttributes() + Attributes attributes = new SecretAttributes() .withEnabled(true) .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); @@ -271,7 +272,7 @@ public void listSecretVersions() throws Exception { keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME); } - private static void validateSecret(SecretBundle secret, String vault, String name, String value, String contentType, SecretAttributes attributes) throws Exception { + private static void validateSecret(SecretBundle secret, String vault, String name, String value, String contentType, Attributes attributes) throws Exception { String prefix = vault + "/secrets/" + name + "/"; String id = secret.id(); Assert.assertTrue( // @@ -285,6 +286,8 @@ private static void validateSecret(SecretBundle secret, String vault, String nam Assert.assertNotNull("\"updated\" should not be null.", secret.attributes().updated()); compareAttributes(attributes, secret.attributes()); + + Assert.assertTrue(secret.managed() == null || secret.managed() == false); } private void compareSecrets(SecretBundle expected, SecretBundle actual) { @@ -296,6 +299,7 @@ private void compareSecrets(SecretBundle expected, SecretBundle actual) { Assert.assertEquals(expected.attributes().notBefore(), actual.attributes().notBefore()); if(expected.tags() != null || actual.tags() != null) Assert.assertTrue(expected.tags().equals(actual.tags())); + } } From 2e7ded31c63c72268e948b2428f729fa8bb29dac Mon Sep 17 00:00:00 2001 From: Hervey Wilson Date: Mon, 22 Aug 2016 13:46:46 -0700 Subject: [PATCH 05/14] Crypto test cases for excess key material support to match .NET --- .../keyvault/cryptography/Algorithm.java | 25 +++ .../cryptography/algorithms/Aes128Cbc.java | 50 +++++ .../cryptography/algorithms/Aes192Cbc.java | 51 +++++ .../cryptography/algorithms/Aes256Cbc.java | 51 +++++ .../cryptography/algorithms/AesKw128.java | 19 +- .../cryptography/algorithms/AesKw192.java | 19 +- .../cryptography/algorithms/AesKw256.java | 19 +- .../cryptography/test/AesCbcTest.java | 185 +++++++++++++++--- .../keyvault/cryptography/test/AesKwTest.java | 178 +++++++++++++++++ .../test/SymmetricKeyBCProviderTest.java | 2 +- .../test/SymmetricKeyDefaultProviderTest.java | 29 --- ...KeyBaseTest.java => SymmetricKeyTest.java} | 173 +++++++++++++++- 12 files changed, 719 insertions(+), 82 deletions(-) delete mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java rename azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/{SymmetricKeyBaseTest.java => SymmetricKeyTest.java} (69%) diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java index bfdcf9e54e790..127521c7d4373 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java @@ -33,4 +33,29 @@ protected Algorithm(String name) { public String getName() { return _name; } + + /* + * Takes the first count bytes from the source and + * returns a new array containing those bytes. + * + * @param count The number of bytes to take. + * @param source The source of the bytes. + * @return count bytes from the source as a new array. + */ + public static byte[] Take(int count, byte[] source) + { + if ( source == null ) { + throw new IllegalArgumentException("source"); + } + + if ( count <= 0 || count > source.length ) { + throw new IllegalArgumentException("count"); + } + + byte[] target = new byte[count]; + + System.arraycopy(source, 0, target, 0, count); + + return target; + } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java index 206a463d5b7ef..c0a5630e8df6b 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java @@ -18,12 +18,62 @@ package com.microsoft.azure.keyvault.cryptography.algorithms; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + public class Aes128Cbc extends AesCbc { public static final String AlgorithmName = "A128CBC"; + + static final int KeySizeInBytes = 128 >> 3; public Aes128Cbc() { super(AlgorithmName); } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java index 2cb0fc22b4d96..96b03caf970e0 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java @@ -18,12 +18,63 @@ package com.microsoft.azure.keyvault.cryptography.algorithms; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + public class Aes192Cbc extends AesCbc { public static final String AlgorithmName = "A192CBC"; + + static final int KeySizeInBytes = 192 >> 3; public Aes192Cbc() { super(AlgorithmName); } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java index 91fb58e09c932..88abe788ee757 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java @@ -18,12 +18,63 @@ package com.microsoft.azure.keyvault.cryptography.algorithms; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + public class Aes256Cbc extends AesCbc { public static final String AlgorithmName = "A256CBC"; + + static final int KeySizeInBytes = 256 >> 3; public Aes256Cbc() { super(AlgorithmName); } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null || key.length < KeySizeInBytes) { + throw new InvalidKeyException("key must be at least 128 bits in length"); + } + + return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java index 5d7a15605aea6..2044f10895867 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java @@ -21,6 +21,7 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.security.Provider; import javax.crypto.NoSuchPaddingException; @@ -29,37 +30,39 @@ public final class AesKw128 extends AesKw { public static final String AlgorithmName = "A128KW"; + + static final int KeySizeInBytes = 128 >> 3; public AesKw128() { super(AlgorithmName); } @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { if (key == null) { throw new IllegalArgumentException("key must not be null"); } - if (key.length << 3 != 128) { - throw new IllegalArgumentException("key must be 128 bits long"); + if (key.length < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 128 bits long"); } - return super.CreateEncryptor(key, iv); + return super.CreateEncryptor(Take(KeySizeInBytes,key), iv, provider); } @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { if (key == null) { throw new IllegalArgumentException("key must not be null"); } - if (key.length << 3 != 128) { - throw new IllegalArgumentException("key must be 128 bits long"); + if (key.length < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 128 bits long"); } - return super.CreateDecryptor(key, iv); + return super.CreateDecryptor(Take(KeySizeInBytes,key), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java index f20f5ec7ee22c..bb652553ff83e 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java @@ -21,6 +21,7 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.security.Provider; import javax.crypto.NoSuchPaddingException; @@ -29,37 +30,39 @@ public final class AesKw192 extends AesKw { public static final String AlgorithmName = "A192KW"; + + static final int KeySizeInBytes = 192 >> 3; public AesKw192() { super(AlgorithmName); } @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { if (key == null) { throw new IllegalArgumentException("key must not be null"); } - if (key.length << 3 != 192) { - throw new IllegalArgumentException("key must be 192 bits long"); + if (key.length < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 192 bits long"); } - return super.CreateEncryptor(key, iv); + return super.CreateEncryptor(Take(KeySizeInBytes,key), iv, provider); } @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { if (key == null) { throw new IllegalArgumentException("key must not be null"); } - if (key.length << 3 != 192) { - throw new IllegalArgumentException("key must be 192 bits long"); + if (key.length < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 192 bits long"); } - return super.CreateDecryptor(key, iv); + return super.CreateDecryptor(Take(KeySizeInBytes,key), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java index c4b23a572c222..b2ed7dd4815f7 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java @@ -21,6 +21,7 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.security.Provider; import javax.crypto.NoSuchPaddingException; @@ -29,37 +30,39 @@ public final class AesKw256 extends AesKw { public static final String AlgorithmName = "A256KW"; + + static final int KeySizeInBytes = 256 >> 3; public AesKw256() { super(AlgorithmName); } @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { if (key == null) { throw new IllegalArgumentException("key must not be null"); } - if (key.length << 3 != 256) { - throw new IllegalArgumentException("key must be 256 bits long"); + if (key.length < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 256 bits long"); } - return super.CreateEncryptor(key, iv); + return super.CreateEncryptor(Take(KeySizeInBytes,key), iv, provider); } @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { if (key == null) { throw new IllegalArgumentException("key must not be null"); } - if (key.length << 3 != 256) { - throw new IllegalArgumentException("key must be 256 bits long"); + if (key.length < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 256 bits long"); } - return super.CreateDecryptor(key, iv); + return super.CreateDecryptor(Take(KeySizeInBytes,key), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java index 53286b5471690..6498b9508dff6 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java @@ -11,6 +11,7 @@ import org.junit.BeforeClass; import org.junit.Test; +import com.microsoft.azure.keyvault.cryptography.Algorithm; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; @@ -40,44 +41,130 @@ protected void setProvider(Provider provider) { } @Test - public void testAes128Cbc() { - // Arrange: These values are taken from Appendix B of the JWE - // specification at - // https://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-40#appendix-B - // Since the values were intended for use with AES128-CBC-HMAC-SHA2 we - // actually take the realCEK from the second half of the CEK data below - // in order - // that the encrypted result will match the ED value from the example. - byte[] CEK = { 4, (byte) 211, 31, (byte) 197, 84, (byte) 157, (byte) 252, (byte) 254, 11, 100, (byte) 157, (byte) 250, 63, (byte) 170, 106, (byte) 206, 107, 124, (byte) 212, 45, 111, 107, 9, (byte) 219, (byte) 200, (byte) 177, 0, (byte) 240, (byte) 143, (byte) 156, 44, (byte) 207 }; - byte[] PLAIN = { 76, 105, 118, 101, 32, 108, 111, 110, 103, 32, 97, 110, 100, 32, 112, 114, 111, 115, 112, 101, 114, 46 }; - byte[] IV = { 3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101 }; - //byte[] AUTH = { 101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 66, 77, 84, 73, 52, 83, 49, 99, 105, 76, 67, 74, 108, 98, 109, 77, 105, 79, 105, 74, 66, 77, 84, 73, 52, 81, 48, 74, 68, 76, 85, 104, 84, 77, 106, 85, 50, 73, 110, 48 }; - byte[] ED = { 40, 57, 83, (byte) 181, 119, 33, (byte) 133, (byte) 148, (byte) 198, (byte) 185, (byte) 243, 24, (byte) 152, (byte) 230, 6, 75, (byte) 129, (byte) 223, 127, 19, (byte) 210, 82, (byte) 183, (byte) 230, (byte) 168, 33, (byte) 215, 104, (byte) 143, 112, 56, 102 }; - //byte[] TAG = { 83, 73, (byte) 191, 98, 104, (byte) 205, (byte) 211, (byte) 128, (byte) 201, (byte) 189, (byte) 199, (byte) 133, 32, 38, (byte) 194, 85 }; - - Aes128Cbc algo = new Aes128Cbc(); - byte[] realCEK = new byte[128 >> 3]; - byte[] encrypted = null; - - // Take the second half of CEK as the AES key - System.arraycopy(CEK, 128 >> 3, realCEK, 0, 128 >> 3); + public void testAes128CbcOneBlock() { + // Note that AES128CBC as implemented in this library uses PKCS7 padding mode where the test + // vectors from RFC3602 do not use padding. + byte[] CEK = { 0x06, (byte)0xa9, 0x21, 0x40, 0x36, (byte)0xb8, (byte)0xa1, 0x5b, 0x51, 0x2e, 0x03, (byte)0xd5, 0x34, 0x12, 0x00, 0x06 }; + byte[] PLAIN = "Single block msg".getBytes(); + byte[] IV = { 0x3d, (byte)0xaf, (byte)0xba, 0x42, (byte)0x9d, (byte)0x9e, (byte)0xb4, 0x30, (byte)0xb4, 0x22, (byte)0xda, (byte)0x80, 0x2c, (byte)0x9f, (byte)0xac, 0x41 }; + byte[] ED = { (byte)0xe3, 0x53, 0x77, (byte)0x9c, 0x10, 0x79, (byte)0xae, (byte)0xb8, 0x27, 0x08, (byte)0x94, 0x2d, (byte)0xbe, 0x77, 0x18, 0x1a }; + + Aes128Cbc algo = new Aes128Cbc(); + byte[] encrypted = null; + + ICryptoTransform encryptor = null; + try { + encryptor = algo.CreateEncryptor(CEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + encrypted = encryptor.doFinal(PLAIN); + + // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(16,encrypted),ED); + } catch (Exception e) { + fail(e.getMessage()); + } + + ICryptoTransform decryptor = null; + try { + decryptor = algo.CreateDecryptor(CEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = decryptor.doFinal(encrypted); + + // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(16, decrypted), PLAIN); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testAes128CbcTwoBlock() { + // Note that AES128CBC as implemented in this library uses PKCS7 padding mode where the test + // vectors do not use padding. + byte[] CEK = { (byte)0xc2, (byte)0x86, 0x69, 0x6d, (byte)0x88, 0x7c, (byte)0x9a, (byte)0xa0, 0x61, 0x1b, (byte)0xbb, 0x3e, 0x20, 0x25, (byte)0xa4, 0x5a }; + byte[] PLAIN = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; + byte[] IV = { 0x56, 0x2e, 0x17, (byte)0x99, 0x6d, 0x09, 0x3d, 0x28, (byte)0xdd, (byte)0xb3, (byte)0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58 }; + byte[] ED = { (byte)0xd2, (byte)0x96, (byte)0xcd, (byte)0x94, (byte)0xc2, (byte)0xcc, (byte)0xcf, (byte)0x8a, 0x3a, (byte)0x86, 0x30, 0x28, (byte)0xb5, (byte)0xe1, (byte)0xdc, 0x0a, 0x75, (byte)0x86, 0x60, 0x2d, 0x25, 0x3c, (byte)0xff, (byte)0xf9, 0x1b, (byte)0x82, 0x66, (byte)0xbe, (byte)0xa6, (byte)0xd6, 0x1a, (byte)0xb1 }; + + Aes128Cbc algo = new Aes128Cbc(); + byte[] encrypted = null; + + ICryptoTransform encryptor = null; + try { + encryptor = algo.CreateEncryptor(CEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + encrypted = encryptor.doFinal(PLAIN); + + // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(32,encrypted),ED); + } catch (Exception e) { + fail(e.getMessage()); + } + + ICryptoTransform decryptor = null; + try { + decryptor = algo.CreateDecryptor(CEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = decryptor.doFinal(encrypted); + + // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(32, decrypted), PLAIN); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testAes128CbcOneBlock_ExcessKeyMaterial() { + // Note that AES128CBC as implemented in this library uses PKCS7 padding mode where the test + // vectors from RFC3602 do not use padding. + byte[] CEK = { 0x06, (byte)0xa9, 0x21, 0x40, 0x36, (byte)0xb8, (byte)0xa1, 0x5b, 0x51, 0x2e, 0x03, (byte)0xd5, 0x34, 0x12, 0x00, 0x06, (byte)0xc2, (byte)0x86, 0x69, 0x6d, (byte)0x88, 0x7c, (byte)0x9a, (byte)0xa0, 0x61, 0x1b, (byte)0xbb, 0x3e, 0x20, 0x25, (byte)0xa4, 0x5a }; + byte[] PLAIN = "Single block msg".getBytes(); + byte[] IV = { 0x3d, (byte)0xaf, (byte)0xba, 0x42, (byte)0x9d, (byte)0x9e, (byte)0xb4, 0x30, (byte)0xb4, 0x22, (byte)0xda, (byte)0x80, 0x2c, (byte)0x9f, (byte)0xac, 0x41 }; + byte[] ED = { (byte)0xe3, 0x53, 0x77, (byte)0x9c, 0x10, 0x79, (byte)0xae, (byte)0xb8, 0x27, 0x08, (byte)0x94, 0x2d, (byte)0xbe, 0x77, 0x18, 0x1a }; + + Aes128Cbc algo = new Aes128Cbc(); + byte[] encrypted = null; ICryptoTransform encryptor = null; try { - encryptor = algo.CreateEncryptor(realCEK, IV, null, _provider); + encryptor = algo.CreateEncryptor(CEK, IV, null, _provider); } catch (Exception e) { fail(e.getMessage()); } try { encrypted = encryptor.doFinal(PLAIN); + + // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(16,encrypted),ED); } catch (Exception e) { fail(e.getMessage()); } ICryptoTransform decryptor = null; try { - decryptor = algo.CreateDecryptor(realCEK, IV, null, _provider); + decryptor = algo.CreateDecryptor(CEK, IV, null, _provider); } catch (Exception e) { fail(e.getMessage()); } @@ -86,12 +173,58 @@ public void testAes128Cbc() { try { decrypted = decryptor.doFinal(encrypted); + + // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(16, decrypted), PLAIN); } catch (Exception e) { fail(e.getMessage()); } + } - // Assert - assertArrayEquals(PLAIN, decrypted); - assertArrayEquals(ED, encrypted); + @Test + public void testAes128CbcTwoBlock_ExcessKeyMaterial() { + // Note that AES128CBC as implemented in this library uses PKCS7 padding mode where the test + // vectors do not use padding. + byte[] CEK = { (byte)0xc2, (byte)0x86, 0x69, 0x6d, (byte)0x88, 0x7c, (byte)0x9a, (byte)0xa0, 0x61, 0x1b, (byte)0xbb, 0x3e, 0x20, 0x25, (byte)0xa4, 0x5a, (byte)0xc2, (byte)0x86, 0x69, 0x6d, (byte)0x88, 0x7c, (byte)0x9a, (byte)0xa0, 0x61, 0x1b, (byte)0xbb, 0x3e, 0x20, 0x25, (byte)0xa4, 0x5a }; + byte[] PLAIN = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; + byte[] IV = { 0x56, 0x2e, 0x17, (byte)0x99, 0x6d, 0x09, 0x3d, 0x28, (byte)0xdd, (byte)0xb3, (byte)0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58 }; + byte[] ED = { (byte)0xd2, (byte)0x96, (byte)0xcd, (byte)0x94, (byte)0xc2, (byte)0xcc, (byte)0xcf, (byte)0x8a, 0x3a, (byte)0x86, 0x30, 0x28, (byte)0xb5, (byte)0xe1, (byte)0xdc, 0x0a, 0x75, (byte)0x86, 0x60, 0x2d, 0x25, 0x3c, (byte)0xff, (byte)0xf9, 0x1b, (byte)0x82, 0x66, (byte)0xbe, (byte)0xa6, (byte)0xd6, 0x1a, (byte)0xb1 }; + + Aes128Cbc algo = new Aes128Cbc(); + byte[] encrypted = null; + + ICryptoTransform encryptor = null; + try { + encryptor = algo.CreateEncryptor(CEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + encrypted = encryptor.doFinal(PLAIN); + + // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(32,encrypted),ED); + } catch (Exception e) { + fail(e.getMessage()); + } + + ICryptoTransform decryptor = null; + try { + decryptor = algo.CreateDecryptor(CEK, IV, null, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = decryptor.doFinal(encrypted); + + // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding + assertArrayEquals(Algorithm.Take(32, decrypted), PLAIN); + } catch (Exception e) { + fail(e.getMessage()); + } } } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java index d22e2107ce6ef..e79e5569fe71c 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java @@ -248,4 +248,182 @@ public void KeyVault_AesKw256() { } } + @Test + public void KeyVault_AesKw128_ExcessKeyMaterial() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + 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[] 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 }; + + AesKw kw = new AesKw128(); + + ICryptoTransform encryptor = null; + + try { + encryptor = kw.CreateEncryptor(KEK, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] encrypted = null; + + try { + encrypted = encryptor.doFinal(CEK); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + + ICryptoTransform decryptor = null; + + try { + decryptor = kw.CreateDecryptor(KEK, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = decryptor.doFinal(EK); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + @Test + public void KeyVault_AesKw192_ExcessKeyMaterial() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + 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[] 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 }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + AesKw kw = new AesKw192(); + + ICryptoTransform encryptor = null; + + try { + encryptor = kw.CreateEncryptor(KEK, _provider); + + if (!unlimited) fail("Expected InvalidKeyException"); + } catch (InvalidKeyException e) { + if (unlimited) fail("InvalidKeyException"); + } catch (Exception e) { + fail(e.getMessage()); + } + + if (unlimited) { + byte[] encrypted = null; + + try { + encrypted = encryptor.doFinal(CEK); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + + ICryptoTransform decryptor = null; + + try { + decryptor = kw.CreateDecryptor(KEK, _provider); + if (!unlimited) fail("Expected InvalidKeyException"); + } catch (InvalidKeyException e) { + if (unlimited) fail("InvalidKeyException"); + } catch (Exception e) { + fail(e.getMessage()); + } + + if (unlimited) { + byte[] decrypted = null; + + try { + decrypted = decryptor.doFinal(EK); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + } + + @Test + public void KeyVault_AesKw256_ExcessKeyMaterial() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + 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[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + AesKw kw = new AesKw256(); + + ICryptoTransform encryptor = null; + + try { + encryptor = kw.CreateEncryptor(KEK, _provider); + if (!unlimited) fail("Expected InvalidKeyException"); + } catch (InvalidKeyException e) { + if (unlimited) fail("InvalidKeyException"); + } catch (Exception e) { + fail(e.getMessage()); + } + + if (unlimited) { + byte[] encrypted = null; + + try { + encrypted = encryptor.doFinal(CEK); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + + ICryptoTransform decryptor = null; + + try { + decryptor = kw.CreateDecryptor(KEK, _provider); + + if (!unlimited) fail("Expected InvalidKeyException"); + } catch (InvalidKeyException e) { + if (unlimited) fail("InvalidKeyException"); + } catch (Exception e) { + fail(e.getMessage()); + } + + if (unlimited) { + byte[] decrypted = null; + + try { + decrypted = decryptor.doFinal(EK); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + } + } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java index a6a7936c9fa65..2954df416105f 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java @@ -21,7 +21,7 @@ import java.security.Provider; import org.junit.Before; -public class SymmetricKeyBCProviderTest extends SymmetricKeyBaseTest { +public class SymmetricKeyBCProviderTest extends SymmetricKeyTest { @Before public void setUp() throws Exception { diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java deleted file mode 100644 index 384961ad2e643..0000000000000 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.microsoft.azure.keyvault.cryptography.test; - -import org.junit.Before; - -public class SymmetricKeyDefaultProviderTest extends SymmetricKeyBaseTest { - - @Before - public void setUp() throws Exception { - super.setProvider(null); - } -} diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java similarity index 69% rename from azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java rename to azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java index 36b6bf464aa16..b6d3194cae058 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBaseTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java @@ -37,7 +37,7 @@ import com.microsoft.azure.keyvault.cryptography.SymmetricKey; -public abstract class SymmetricKeyBaseTest { +public class SymmetricKeyTest { private Provider _provider = null; @@ -58,7 +58,9 @@ public static void tearDownAfterClass() throws Exception { } @Before - public abstract void setUp() throws Exception; + public void setUp() throws Exception { + setProvider(null); + } @After public void tearDown() throws Exception { @@ -420,4 +422,171 @@ public void testSymmetricKeyDefaultAlgorithmAesKw256() { } } + @Test + public void testSymmetricKeyAesKw128_ExcessKeyMaterial() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + 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[] 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 }; + + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A128KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyAesKw192_ExcessKeyMaterial() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + 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[] 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 }; + + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyAesKw256_ExcessKeyMaterial() { + // Arrange + 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, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + 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[] EK = { 0x64, (byte)0xE8, (byte)0xC3, (byte)0xF9, (byte)0xCE, 0x0F, 0x5B, (byte)0xA2, 0x63, (byte)0xE9, 0x77, 0x79, 0x05, (byte)0x81, (byte)0x8A, 0x2A, (byte)0x93, (byte)0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte)0x8A, (byte)0xE7 }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A256KW").get().getLeft(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A256KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } } From 8f04f77a6331d9c2cd240c97b412d7d594d49318 Mon Sep 17 00:00:00 2001 From: Pooneh Date: Tue, 23 Aug 2016 11:25:18 -0700 Subject: [PATCH 06/14] Refactoring JSON web key to KV webkey project --- azure-keyvault-cryptography/pom.xml | 61 ++- .../test/Base64UrlDeserializer.java | 43 --- .../cryptography/test/JsonWebKey.java | 346 ------------------ .../cryptography/test/JsonWebKeyType.java | 40 -- .../cryptography/test/RsaKeyTest.java | 1 + azure-keyvault-extensions/pom.xml | 5 + .../keyvault/extensions/KeyVaultKey.java | 2 +- azure-keyvault-webkey/pom.xml | 104 ++++++ .../webkey/Base64UrlJsonDeserializer.java | 34 ++ .../webkey/Base64UrlJsonSerializer.java | 25 +- .../azure/keyvault/webkey}/JsonWebKey.java | 337 ++++++++--------- .../webkey/JsonWebKeyEncryptionAlgorithm.java | 18 +- .../keyvault/webkey/JsonWebKeyOperation.java | 18 +- .../webkey/JsonWebKeySignatureAlgorithm.java | 18 +- .../azure/keyvault/webkey/JsonWebKeyType.java | 18 +- .../azure/keyvault/webkey/package-info.java | 3 +- azure-keyvault/pom.xml | 5 + .../azure/keyvault/KeyVaultClientImpl.java | 4 +- .../azure/keyvault/models/KeyBundle.java | 1 + .../keyvault/models/KeyImportParameters.java | 1 + .../keyvault/requests/ImportKeyRequest.java | 2 +- .../keyvault/test/AsyncOperationsTest.java | 44 ++- .../keyvault/test/KeyOperationsTest.java | 2 +- 23 files changed, 395 insertions(+), 737 deletions(-) delete mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java delete mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java delete mode 100644 azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java create mode 100644 azure-keyvault-webkey/pom.xml create mode 100644 azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java rename azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java => azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java (50%) rename {azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models => azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey}/JsonWebKey.java (60%) rename {azure-keyvault => azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java (54%) rename {azure-keyvault => azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java (63%) rename {azure-keyvault => azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java (59%) rename {azure-keyvault => azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java (58%) rename {azure-keyvault => azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java (58%) diff --git a/azure-keyvault-cryptography/pom.xml b/azure-keyvault-cryptography/pom.xml index 5b7688e30a0db..b3e1236542df2 100644 --- a/azure-keyvault-cryptography/pom.xml +++ b/azure-keyvault-cryptography/pom.xml @@ -34,40 +34,35 @@ HEAD - - UTF-8 - - - true - + + UTF-8 + + + true + - - - junit - junit - test - - - org.bouncycastle - bcprov-jdk15on - test - 1.54 - - + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk15on + test + 1.54 + + ${project.groupId} - azure-keyvault-core - ${project.version} - - - com.fasterxml.jackson.core - jackson-databind - test - - - commons-codec - commons-codec - test - - + azure-keyvault-core + ${project.version} + + + ${project.groupId} + azure-keyvault-webkey + ${project.version} + + diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java deleted file mode 100644 index 8f54e8cdece21..0000000000000 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlDeserializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.microsoft.azure.keyvault.cryptography.test; - -import java.io.IOException; - -import org.apache.commons.codec.binary.Base64; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; - -public class Base64UrlDeserializer extends JsonDeserializer { - - static final Base64 _base64 = new Base64(-1, null, true); - - @Override - public byte[] deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - String text = jp.getText(); - if (text != null) { - return _base64.decode(text); - } - return null; - } - -} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java deleted file mode 100644 index ec65f0d6fea55..0000000000000 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKey.java +++ /dev/null @@ -1,346 +0,0 @@ -/** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.microsoft.azure.keyvault.cryptography.test; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPrivateKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.util.Arrays; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY, setterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) -public class JsonWebKey { - - private String kid; - - @JsonProperty("kid") - public String getKid() { - return kid; - } - - public void setKid(String kid) { - this.kid = kid; - } - - private String kty; - - @JsonProperty("kty") - public String getKty() { - return kty; - } - - public void setKty(String kty) { - this.kty = kty; - } - - private String[] keyOps; - - @JsonProperty("key_ops") - public String[] getKeyOps() { - return keyOps; - } - - public void setKeyOps(String[] keyOps) { - this.keyOps = keyOps; - } - - private byte[] n; - - @JsonProperty("n") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getN() { - return n; - } - - public void setN(byte[] n) { - this.n = n; - } - - private byte[] e; - - @JsonProperty("e") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getE() { - return e; - } - - public void setE(byte[] e) { - this.e = e; - } - - private byte[] d; - - @JsonProperty("d") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getD() { - return d; - } - - public void setD(byte[] d) { - this.d = d; - } - - private byte[] dp; - - @JsonProperty("dp") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getDP() { - return dp; - } - - public void setDP(byte[] dp) { - this.dp = dp; - } - - private byte[] dq; - - @JsonProperty("dq") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getDQ() { - return dq; - } - - public void setDQ(byte[] dq) { - this.dq = dq; - } - - private byte[] qi; - - @JsonProperty("qi") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getQI() { - return qi; - } - - public void setQI(byte[] qi) { - this.qi = qi; - } - - private byte[] p; - - @JsonProperty("p") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getP() { - return p; - } - - public void setP(byte[] p) { - this.p = p; - } - - private byte[] q; - - @JsonProperty("q") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getQ() { - return q; - } - - public void setQ(byte[] q) { - this.q = q; - } - - private byte[] k; - - @JsonProperty("k") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getk() { - return k; - } - - public void setK(byte[] k) { - this.k = k; - } - - private byte[] t; - - @JsonProperty("key_hsm") - @JsonSerialize(using = Base64UrlSerializer.class) - @JsonDeserialize(using = Base64UrlDeserializer.class) - public byte[] getT() { - return t; - } - - public void setT(byte[] t) { - this.t = t; - } - - @Override - public String toString() { - ObjectMapper mapper = new ObjectMapper(); - try { - return mapper.writeValueAsString(this); - } catch (JsonGenerationException e) { - throw new IllegalStateException(e); - } catch (JsonMappingException e) { - throw new IllegalStateException(e); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - private RSAPublicKeySpec getRSAPublicKeySpec() { - - return new RSAPublicKeySpec(toBigInteger(n), toBigInteger(e)); - } - - private RSAPrivateKeySpec getRSAPrivateKeySpec() { - - return new RSAPrivateCrtKeySpec(toBigInteger(n), toBigInteger(e), toBigInteger(d), toBigInteger(p), toBigInteger(q), toBigInteger(dp), toBigInteger(dq), toBigInteger(qi)); - } - - 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 new IllegalStateException(e); - } - } - - 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 new IllegalStateException(e); - } - } - - private void checkRSACompatible() { - if (!JsonWebKeyType.RSA.equals(kty) && !JsonWebKeyType.RSAHSM.equals(kty)) { - throw 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); - } - - public static JsonWebKey fromRSA(KeyPair keyPair) { - - RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate(); - JsonWebKey key = null; - - if (privateKey != null) { - - key = new JsonWebKey(); - - key.setKty(JsonWebKeyType.RSA); - - key.setN(toByteArray(privateKey.getModulus())); - key.setE(toByteArray(privateKey.getPublicExponent())); - key.setD(toByteArray(privateKey.getPrivateExponent())); - key.setP(toByteArray(privateKey.getPrimeP())); - key.setQ(toByteArray(privateKey.getPrimeQ())); - key.setDP(toByteArray(privateKey.getPrimeExponentP())); - key.setDQ(toByteArray(privateKey.getPrimeExponentQ())); - key.setQI(toByteArray(privateKey.getCrtCoefficient())); - } else { - - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - - key = new JsonWebKey(); - - key.setKty(JsonWebKeyType.RSA); - - key.setN(toByteArray(publicKey.getModulus())); - key.setE(toByteArray(publicKey.getPublicExponent())); - key.setD(null); - key.setP(null); - key.setQ(null); - key.setDP(null); - key.setDQ(null); - key.setQI(null); - } - - return key; - } - - public KeyPair toRSA() { - return this.toRSA(false); - } - - public KeyPair toRSA(boolean includePrivateParameters) { - - return toRSA(includePrivateParameters, null); - } - - 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); - } - } -} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java deleted file mode 100644 index f3b1760652637..0000000000000 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/JsonWebKeyType.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.microsoft.azure.keyvault.cryptography.test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Supported JsonWebKey key types (kty) - */ -public final class JsonWebKeyType { - - public static final String EC = "EC"; - public static final String RSA = "RSA"; - public static final String RSAHSM = "RSA-HSM"; - public static final String OCT = "oct"; - - public static final List ALL_TYPES = Collections.unmodifiableList(Arrays.asList(new String[] { EC, RSA, RSAHSM, OCT })); - - private JsonWebKeyType() { - // not instantiable - } -} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java index 7c9b29b956bd5..454752d7bac8b 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -19,6 +19,7 @@ import com.microsoft.azure.keyvault.cryptography.algorithms.Rs256; import com.microsoft.azure.keyvault.cryptography.algorithms.Rsa15; import com.microsoft.azure.keyvault.cryptography.algorithms.RsaOaep; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; public class RsaKeyTest { diff --git a/azure-keyvault-extensions/pom.xml b/azure-keyvault-extensions/pom.xml index 3c9f92ea238a1..36d1dc3668e0a 100644 --- a/azure-keyvault-extensions/pom.xml +++ b/azure-keyvault-extensions/pom.xml @@ -81,6 +81,11 @@ azure-keyvault ${project.version} + + ${project.groupId} + azure-keyvault-webkey + ${project.version} + org.mockito mockito-core diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java index c33fb8eefbabe..2ef3291cfca3a 100644 --- a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java @@ -29,7 +29,7 @@ import com.microsoft.azure.keyvault.KeyVaultClient; import com.microsoft.azure.keyvault.core.IKey; import com.microsoft.azure.keyvault.cryptography.RsaKey; -import com.microsoft.azure.keyvault.models.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyOperationResult; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; diff --git a/azure-keyvault-webkey/pom.xml b/azure-keyvault-webkey/pom.xml new file mode 100644 index 0000000000000..698622c6d1fe0 --- /dev/null +++ b/azure-keyvault-webkey/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + + com.microsoft.azure + azure-parent + 1.0.0-SNAPSHOT + ../pom.xml + + + azure-keyvault-webkey + jar + + Microsoft Azure SDK for Key Vault WebKey + This package contains Microsoft Azure Key Vault WebKey library. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + UTF-8 + + + + + + microsoft + Microsoft + + + + + + + com.fasterxml.jackson.core + jackson-databind + + + commons-codec + commons-codec + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + com.microsoft.schemas._2003._10.serialization; + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/]]>
+
+
+ +
+
+
diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java new file mode 100644 index 0000000000000..18967a8863809 --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.webkey; + +import java.io.IOException; + +import org.apache.commons.codec.binary.Base64; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +/** + * The base64 URL JSON deserializer. + */ +public class Base64UrlJsonDeserializer extends JsonDeserializer { + + static final Base64 _base64 = new Base64(-1, null, true); + + @Override + public byte[] deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + String text = jp.getText(); + if (text != null) { + return _base64.decode(text); + } + return null; + } + +} \ No newline at end of file diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java similarity index 50% rename from azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java index 3cf15e392863d..3613a1aa79199 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/Base64UrlSerializer.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java @@ -1,22 +1,10 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ -package com.microsoft.azure.keyvault.cryptography.test; +package com.microsoft.azure.keyvault.webkey; import java.io.IOException; @@ -27,7 +15,10 @@ import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; -public class Base64UrlSerializer extends JsonSerializer { +/** + * The base64 URL JSON serializer. + */ +public class Base64UrlJsonSerializer extends JsonSerializer { static final Base64 _base64 = new Base64(-1, null, true); diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java similarity index 60% rename from azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java index ef267481ebba1..e6670116cf5e4 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKey.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java @@ -1,14 +1,10 @@ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 - * Changes may cause incorrect behavior and will be lost if the code is - * regenerated. + * license information. */ -package com.microsoft.azure.keyvault.models; +package com.microsoft.azure.keyvault.webkey; import java.io.IOException; import java.math.BigInteger; @@ -16,6 +12,7 @@ import java.security.KeyFactory; import java.security.KeyPair; import java.security.PrivateKey; +import java.security.Provider; import java.security.PublicKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; @@ -24,18 +21,21 @@ import java.security.spec.RSAPublicKeySpec; import java.util.Arrays; import java.util.List; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; -import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; -import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18. */ +@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY, setterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public class JsonWebKey { + /** * Key Identifier. */ @@ -50,73 +50,72 @@ public class JsonWebKey { /** * The keyOps property. */ - @JsonProperty(value = "key_ops") private List keyOps; /** * RSA modulus. */ - private Base64Url n; + private byte[] n; /** * RSA public exponent. */ - private Base64Url e; + private byte[] e; /** * RSA private exponent. */ - private Base64Url d; + private byte[] d; /** * RSA Private Key Parameter. */ - private Base64Url dp; + private byte[] dp; /** * RSA Private Key Parameter. */ - private Base64Url dq; + private byte[] dq; /** * RSA Private Key Parameter. */ - private Base64Url qi; + private byte[] qi; /** * RSA secret prime. */ - private Base64Url p; + private byte[] p; /** * RSA secret prime, with p < q. */ - private Base64Url q; + private byte[] q; /** * Symmetric key. */ - private Base64Url k; + private byte[] k; /** * HSM Token, used with Bring Your Own Key. */ - @JsonProperty(value = "key_hsm") - private Base64Url t; + private byte[] t; /** - * Get the kid value. + * Key Identifier. * - * @return the kid value + * @return the kid value. */ + @JsonProperty("kid") public String kid() { return this.kid; } /** - * Set the kid value. + * Set the key identifier value. * - * @param kid the kid value to set + * @param kid the key identifier * @return the JsonWebKey object itself. */ public JsonWebKey withKid(String kid) { @@ -125,18 +124,20 @@ public JsonWebKey withKid(String kid) { } /** - * Get the kty value. + * Key type, usually RSA. Possible values include: 'EC', 'RSA', 'RSA-HSM', + * 'oct'. * - * @return the kty value + * @return the key type. */ + @JsonProperty("kty") public String kty() { return this.kty; } /** - * Set the kty value. + * Set the key type value. * - * @param kty the kty value to set + * @param kty the key type * @return the JsonWebKey object itself. */ public JsonWebKey withKty(String kty) { @@ -145,18 +146,19 @@ public JsonWebKey withKty(String kty) { } /** - * Get the keyOps value. + * Get the key operations. * - * @return the keyOps value + * @return the key operations. */ + @JsonProperty("key_ops") public List keyOps() { return this.keyOps; } /** - * Set the keyOps value. + * Set the key operations value. * - * @param keyOps the keyOps value to set + * @param keyOps the key operations value to set * @return the JsonWebKey object itself. */ public JsonWebKey withKeyOps(List keyOps) { @@ -165,279 +167,222 @@ public JsonWebKey withKeyOps(List keyOps) { } /** - * Get the n value. + * Get the RSA modulus value. * - * @return the n value + * @return the RSA modulus value. */ + @JsonProperty("n") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] n() { - if (this.n == null) { - return null; - } - return this.n.getDecodedBytes(); + return this.n; } /** - * Set the n value. + * Set the RSA modulus value. * - * @param n the n value to set + * @param n the RSA modulus value to set * @return the JsonWebKey object itself. */ public JsonWebKey withN(byte[] n) { - if (n == null) { - this.n = null; - } else { - this.n = Base64Url.encode(n); - } + this.n = n; return this; } /** - * Get the e value. - * - * @return the e value + * Get the RSA public exponent value. + * @return the RSA public exponent value. */ + @JsonProperty("e") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] e() { - if (this.e == null) { - return null; - } - return this.e.getDecodedBytes(); + return this.e; } /** - * Set the e value. - * - * @param e the e value to set + * Set the RSA public exponent value. + * + * @param e RSA public exponent value to set * @return the JsonWebKey object itself. */ public JsonWebKey withE(byte[] e) { - if (e == null) { - this.e = null; - } else { - this.e = Base64Url.encode(e); - } + this.e = e; return this; } /** - * Get the d value. - * - * @return the d value + * Get the RSA private exponent value. + * @return the RSA private exponent value. */ + @JsonProperty("d") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] d() { - if (this.d == null) { - return null; - } - return this.d.getDecodedBytes(); + return this.d; } /** - * Set the d value. - * - * @param d the d value to set + * Set RSA private exponent value. + * + * @param d the RSA private exponent value to set. * @return the JsonWebKey object itself. */ public JsonWebKey withD(byte[] d) { - if (d == null) { - this.d = null; - } else { - this.d = Base64Url.encode(d); - } + this.d = d; return this; } /** - * Get the dp value. - * - * @return the dp value + * Get the RSA Private Key Parameter value. + * @return the RSA Private Key Parameter value. */ + @JsonProperty("dp") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] dp() { - if (this.dp == null) { - return null; - } - return this.dp.getDecodedBytes(); + return this.dp; } /** - * Set the dp value. - * - * @param dp the dp value to set + * Set RSA Private Key Parameter value + * @param dp the RSA Private Key Parameter value to set. * @return the JsonWebKey object itself. */ public JsonWebKey withDp(byte[] dp) { - if (dp == null) { - this.dp = null; - } else { - this.dp = Base64Url.encode(dp); - } + this.dp = dp; return this; } /** - * Get the dq value. - * - * @return the dq value + * Get the RSA Private Key Parameter value. + * @return the RSA Private Key Parameter value. */ + @JsonProperty("dq") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] dq() { - if (this.dq == null) { - return null; - } - return this.dq.getDecodedBytes(); + return this.dq; } /** - * Set the dq value. - * - * @param dq the dq value to set + * Set RSA Private Key Parameter value . + * @param dq the RSA Private Key Parameter value to set. * @return the JsonWebKey object itself. */ public JsonWebKey withDq(byte[] dq) { - if (dq == null) { - this.dq = null; - } else { - this.dq = Base64Url.encode(dq); - } + this.dq = dq; return this; } /** - * Get the qi value. - * - * @return the qi value + * Get the RSA Private Key Parameter value. + * @return the RSA Private Key Parameter value. */ + @JsonProperty("qi") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] qi() { - if (this.qi == null) { - return null; - } - return this.qi.getDecodedBytes(); + return this.qi; } /** - * Set the qi value. - * - * @param qi the qi value to set + * Set RSA Private Key Parameter value. + * @param qi the RSA Private Key Parameter value to set. * @return the JsonWebKey object itself. */ public JsonWebKey withQi(byte[] qi) { - if (qi == null) { - this.qi = null; - } else { - this.qi = Base64Url.encode(qi); - } + this.qi = qi; return this; } /** - * Get the p value. - * - * @return the p value + * Get the RSA secret prime value. + * @return the RSA secret prime value. */ + @JsonProperty("p") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] p() { - if (this.p == null) { - return null; - } - return this.p.getDecodedBytes(); + return this.p; } /** - * Set the p value. - * - * @param p the p value to set + * Set the RSA secret prime value. + * @param p the RSA secret prime value. * @return the JsonWebKey object itself. */ public JsonWebKey withP(byte[] p) { - if (p == null) { - this.p = null; - } else { - this.p = Base64Url.encode(p); - } + this.p = p; return this; } /** - * Get the q value. - * - * @return the q value + * Get RSA secret prime, with p < q value. + * @return the RSA secret prime, with p < q value. */ + @JsonProperty("q") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] q() { - if (this.q == null) { - return null; - } - return this.q.getDecodedBytes(); + return this.q; } /** - * Set the q value. - * - * @param q the q value to set + * 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 withQ(byte[] q) { - if (q == null) { - this.q = null; - } else { - this.q = Base64Url.encode(q); - } + this.q = q; return this; } /** - * Get the k value. - * - * @return the k value + * Get Symmetric key value. + * @return the symmetric key value. */ + @JsonProperty("k") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] k() { - if (this.k == null) { - return null; - } - return this.k.getDecodedBytes(); + return this.k; } /** - * Set the k value. - * - * @param k the k value to set + * Set the Symmetric key value. + * @param k the symmetric key value to set. * @return the JsonWebKey object itself. */ public JsonWebKey withK(byte[] k) { - if (k == null) { - this.k = null; - } else { - this.k = Base64Url.encode(k); - } + this.k = k; return this; } /** - * Get the t value. - * - * @return the t value + * Get HSM Token value, used with Bring Your Own Key. + * @return HSM Token, used with Bring Your Own Key. */ + @JsonProperty("key_hsm") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] t() { - if (this.t == null) { - return null; - } - return this.t.getDecodedBytes(); + return this.t; } /** - * Set the t value. - * - * @param t the t value to set + * Set HSM Token value, used with Bring Your Own Key. + * @param t HSM Token value to set, used with Bring Your Own Key * @return the JsonWebKey object itself. */ public JsonWebKey withT(byte[] t) { - if (t == null) { - this.t = null; - } else { - this.t = Base64Url.encode(t); - } + this.t = t; return this; } @Override public String toString() { - AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); - ObjectMapper mapper = mapperAdapter.getObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonGenerationException e) { @@ -473,13 +418,14 @@ private RSAPrivateKeySpec getRSAPrivateKeySpec() { /** * Get the RSA public key value. * + * @param provider the Java security provider. * @return the RSA public key value */ - private PublicKey getRSAPublicKey() { + private PublicKey getRSAPublicKey(Provider provider) { try { RSAPublicKeySpec publicKeySpec = getRSAPublicKeySpec(); - KeyFactory factory = KeyFactory.getInstance("RSA"); + KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA"); return factory.generatePublic(publicKeySpec); } catch (GeneralSecurityException e) { @@ -490,13 +436,14 @@ private PublicKey getRSAPublicKey() { /** * Get the RSA private key value. * + * @param provider the Java security provider. * @return the RSA private key value */ - private PrivateKey getRSAPrivateKey() { + private PrivateKey getRSAPrivateKey(Provider provider) { try { RSAPrivateKeySpec privateKeySpec = getRSAPrivateKeySpec(); - KeyFactory factory = KeyFactory.getInstance("RSA"); + KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA"); return factory.generatePrivate(privateKeySpec); } catch (GeneralSecurityException e) { @@ -590,14 +537,24 @@ public KeyPair toRSA() { * @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(), getRSAPrivateKey()); + return new KeyPair(getRSAPublicKey(provider), getRSAPrivateKey(provider)); } else { - return new KeyPair(getRSAPublicKey(), null); + return new KeyPair(getRSAPublicKey(provider), null); } } -} +} \ No newline at end of file diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java similarity index 54% rename from azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java index 96ee1a2d303e8..8eb412e21e412 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.webkey; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java similarity index 63% rename from azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java index 50360fee81496..aeacbc6655ace 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.webkey; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java similarity index 59% rename from azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java index fa9737305d268..0dc97946c274b 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.webkey; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java similarity index 58% rename from azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java index a04d9b3c40540..c5bdf89410d9e 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.webkey; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java similarity index 58% rename from azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java rename to azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java index 30b69d136c2b7..6768bb5045206 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java @@ -3,7 +3,6 @@ // license information. /** - * This package contains the classes for KeyVaultClient. Performs cryptographic - * key operations and vault operations against the Key Vault service. + * This package contains the classes for key vault JSON web key. */ package com.microsoft.azure.keyvault.webkey; diff --git a/azure-keyvault/pom.xml b/azure-keyvault/pom.xml index a1a3830259410..66e34edb30b3e 100644 --- a/azure-keyvault/pom.xml +++ b/azure-keyvault/pom.xml @@ -52,6 +52,11 @@ azure-client-runtime 1.0.0-SNAPSHOT
+ + ${project.groupId} + azure-keyvault-webkey + ${project.version} + diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java index 8b5c045ede14a..4c9e596423269 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java @@ -33,7 +33,6 @@ import com.microsoft.azure.keyvault.models.IssuerAttributes; import com.microsoft.azure.keyvault.models.IssuerBundle; import com.microsoft.azure.keyvault.models.IssuerCredentials; -import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyAttributes; import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyCreateParameters; @@ -54,6 +53,9 @@ import com.microsoft.azure.keyvault.models.SecretItem; import com.microsoft.azure.keyvault.models.SecretSetParameters; import com.microsoft.azure.keyvault.models.SecretUpdateParameters; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.Base64UrlJsonSerializer; +import com.microsoft.azure.keyvault.webkey.Base64UrlJsonDeserializer; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java index ae4a62b7cbacc..e7ce6cc2b0fb1 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java @@ -17,6 +17,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.keyvault.KeyIdentifier; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java index 0cd6eb0a956e5..457486131b8c7 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java @@ -12,6 +12,7 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; /** * The key import parameters. diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java index b644554936253..91adae60c3ce8 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java @@ -5,8 +5,8 @@ import java.util.Map; import com.microsoft.azure.keyvault.models.Attributes; -import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyAttributes; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; /** * The import key request class. diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java index 86410c9ab946f..de8a167ee8eda 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Random; +import java.util.concurrent.ExecutionException; import org.junit.Assert; import org.junit.Test; @@ -39,6 +40,7 @@ import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyItem; import com.microsoft.azure.keyvault.models.KeyOperationResult; +import com.microsoft.azure.keyvault.models.KeyVaultErrorException; import com.microsoft.azure.keyvault.models.KeyVerifyResult; import com.microsoft.azure.keyvault.models.SecretBundle; import com.microsoft.azure.keyvault.models.SecretItem; @@ -115,7 +117,21 @@ public void keyAsync() throws Exception { Assert.assertTrue(verifypResult.value()); keyBundle = keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get().getBody(); - Assert.assertNotNull(keyBundle); + Assert.assertNotNull(keyBundle); + + //Get the unavailable key to throw exception -> it gets stuck + + try { + keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get(); + } catch (ExecutionException ex) { + + Throwable t = ex.getCause(); + if(t instanceof KeyVaultErrorException) + { + Assert.assertEquals("KeyNotFound", ((KeyVaultErrorException) t).getBody().error().code()); + } + else throw ex; + } } @Test @@ -144,6 +160,18 @@ public void secretAsync() throws Exception { secretBundle = keyVaultClient.deleteSecretAsync(vault, secretname, null).get().getBody(); Assert.assertNotNull(secretBundle); + + try { + keyVaultClient.deleteSecretAsync(vault, secretname, null).get(); + } catch (ExecutionException ex) { + + Throwable t = ex.getCause(); + if(t instanceof KeyVaultErrorException) + { + Assert.assertEquals("SecretNotFound", ((KeyVaultErrorException) t).getBody().error().code()); + } + else throw ex; + } } @Test @@ -199,7 +227,19 @@ public void certificateAsync() throws Exception { keyVaultClient.deleteCertificateOperationAsync(vault, certificateName, null).get().getBody(); - keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get().getBody(); + keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get().getBody(); + + try { + keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get(); + } catch (ExecutionException ex) { + + Throwable t = ex.getCause(); + if(t instanceof KeyVaultErrorException) + { + Assert.assertEquals("CertificateNotFound", ((KeyVaultErrorException) t).getBody().error().code()); + } + else throw ex; + } } @Test diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java index c4fd3b4d6209f..219b2202eade1 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -48,8 +48,8 @@ import com.microsoft.azure.keyvault.requests.ImportKeyRequest; import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; import com.microsoft.azure.keyvault.models.Attributes; -import com.microsoft.azure.keyvault.models.JsonWebKey; import com.microsoft.azure.keyvault.models.KeyAttributes; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; From 0acd8913d0e191cb4ff51b466fb5246909fae630 Mon Sep 17 00:00:00 2001 From: Hervey Wilson Date: Wed, 24 Aug 2016 09:56:30 -0700 Subject: [PATCH 07/14] License, documentation and byte array handling update. --- .../microsoft/azure/keyvault/core/IKey.java | 18 +-- .../keyvault/cryptography/Algorithm.java | 57 ++----- .../cryptography/AlgorithmResolver.java | 18 +-- .../AsymmetricEncryptionAlgorithm.java | 76 +++++++-- .../AsymmetricSignatureAlgorithm.java | 18 +-- .../keyvault/cryptography/ByteExtensions.java | 147 ++++++++++++++++++ .../cryptography/EncryptionAlgorithm.java | 26 ++-- .../IAuthenticatedCryptoTransform.java | 18 +-- .../cryptography/ICryptoTransform.java | 34 ++-- .../cryptography/KeyWrapAlgorithm.java | 133 ++++++++++++++-- .../cryptography/SignatureAlgorithm.java | 18 +-- .../azure/keyvault/cryptography/Strings.java | 18 +-- .../SymmetricEncryptionAlgorithm.java | 99 +++++++++--- .../keyvault/cryptography/SymmetricKey.java | 18 +-- .../cryptography/algorithms/Aes128Cbc.java | 27 +--- .../algorithms/Aes128CbcHmacSha256.java | 18 +-- .../cryptography/algorithms/Aes192Cbc.java | 27 +--- .../algorithms/Aes192CbcHmacSha384.java | 18 +-- .../cryptography/algorithms/Aes256Cbc.java | 27 +--- .../algorithms/Aes256CbcHmacSha512.java | 18 +-- .../cryptography/algorithms/AesCbc.java | 18 +-- .../algorithms/AesCbcHmacSha2.java | 18 +-- .../cryptography/algorithms/AesKw.java | 18 +-- .../cryptography/algorithms/AesKw128.java | 23 +-- .../cryptography/algorithms/AesKw192.java | 23 +-- .../cryptography/algorithms/AesKw256.java | 23 +-- .../cryptography/algorithms/Rsa15.java | 18 +-- .../algorithms/RsaEncryption.java | 18 +-- .../cryptography/algorithms/RsaOaep.java | 18 +-- .../cryptography/algorithms/package-info.java | 9 ++ .../cryptography/algorithms/package.html | 5 - .../keyvault/cryptography/package-info.java | 10 ++ .../azure/keyvault/cryptography/package.html | 5 - .../cryptography/test/AesCbcTest.java | 17 +- .../azure/keyvault/CertificateIdentifier.java | 18 +-- .../CertificateOperationIdentifier.java | 18 +-- .../azure/keyvault/IssuerIdentifier.java | 18 +-- .../azure/keyvault/KeyIdentifier.java | 18 +-- .../azure/keyvault/KeyVaultClient.java | 2 +- .../azure/keyvault/ObjectIdentifier.java | 18 +-- .../azure/keyvault/SecretIdentifier.java | 18 +-- .../authentication/ChallengeCache.java | 18 +-- .../authentication/KeyVaultCredentials.java | 18 +-- .../keyvault/test/AsyncOperationsTest.java | 18 +-- .../test/CertificateOperationsTest.java | 18 +-- .../keyvault/test/KeyOperationsTest.java | 18 +-- .../KeyVaultClientIntegrationTestBase.java | 18 +-- .../keyvault/test/SecretOperationsTest.java | 18 +-- 48 files changed, 610 insertions(+), 682 deletions(-) create mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java create mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java delete mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package.html create mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java delete mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package.html diff --git a/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java index 6cf69f7002aa9..5eb18bd42677a 100644 --- a/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java +++ b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.core; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java index 127521c7d4373..e80ccaf5a76b0 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java @@ -1,27 +1,24 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; +/** + * Abstract base class for all Algorithm objects. + * + */ public abstract class Algorithm { private final String _name; + /** + * Constructor. + * + * @param name The name of the algorithm. + */ protected Algorithm(String name) { if (Strings.isNullOrWhiteSpace(name)) { throw new IllegalArgumentException("name"); @@ -30,32 +27,12 @@ protected Algorithm(String name) { _name = name; } - public String getName() { - return _name; - } - - /* - * Takes the first count bytes from the source and - * returns a new array containing those bytes. + /** + * Gets the name of the algorithm. * - * @param count The number of bytes to take. - * @param source The source of the bytes. - * @return count bytes from the source as a new array. + * @return The name of the algorithm. */ - public static byte[] Take(int count, byte[] source) - { - if ( source == null ) { - throw new IllegalArgumentException("source"); - } - - if ( count <= 0 || count > source.length ) { - throw new IllegalArgumentException("count"); - } - - byte[] target = new byte[count]; - - System.arraycopy(source, 0, target, 0, count); - - return target; + public String getName() { + return _name; } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java index c794b02867779..6804aa055420d 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java index 6a01e0333b0f2..b239a41d8530c 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; @@ -25,18 +13,74 @@ import javax.crypto.NoSuchPaddingException; +/** + * Abstract base class for all asymmetric encryption algorithms. + * + */ public abstract class AsymmetricEncryptionAlgorithm extends EncryptionAlgorithm { + /** + * Constructor. + * + * @param name The name of the algorithm. + */ protected AsymmetricEncryptionAlgorithm(String name) { super(name); } + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for encryption that + * uses the specified {@link java.security.KeyPair} and the default {@link java.security.Provider} provider. + * + * @param keyPair + * The key pair to use. + * @return + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + */ public abstract ICryptoTransform CreateEncryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for encryption that + * uses the specified {@link java.security.KeyPair} and {@link java.security.Provider}. + * + * @param keyPair + * The key pair to use. + * @param provider + * The provider to use. + * @return + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + */ public abstract ICryptoTransform CreateEncryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for decryption that + * uses the specified {@link java.security.KeyPair} and the default {@link java.security.Provider} provider. + * + * @param keyPair + * The key pair to use. + * @return + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + */ public abstract ICryptoTransform CreateDecryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for decryption that + * uses the specified {@link java.security.KeyPair} and {@link java.security.Provider}. + * + * @param keyPair + * The key pair to use. + * @param provider + * The provider to use. + * @return + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + */ public abstract ICryptoTransform CreateDecryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException; - } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java index 5232ab646ff4c..ff5e1417ba5c6 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java new file mode 100644 index 0000000000000..c76b4c507de6a --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.cryptography; + +public final class ByteExtensions { + + public 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; + } + + public static byte[] or( byte[] self, byte[] other ) + { + return or( self, other, 0 ); + } + + public static byte[] or( byte[] self, byte[] other, int offset ) + { + if ( self == null ) + throw new IllegalArgumentException( "self" ); + + if ( other == null ) + throw new IllegalArgumentException( "other" ); + + if ( self.length > other.length - offset ) + throw new IllegalArgumentException( "self and other lengths do not match" ); + + byte[] result = new byte[self.length]; + + for ( int i = 0; i < self.length; i++ ) + { + result[i] = (byte)( self[i] | other[offset + i] ); + } + + return result; + } + + public static byte[] xor( byte[] self, byte[] other ) { + return xor( self, other, 0, false ); + } + + public static byte[] xor( byte[] self, byte[] other, boolean inPlace ) + { + return xor( self, other, 0, inPlace ); + } + + public static byte[] xor( byte[] self, byte[] other, int offset ) { + return xor( self, other, 0, false ); + } + + public static byte[] xor( byte[] self, byte[] other, int offset, boolean inPlace ) + { + if ( self == null ) + throw new IllegalArgumentException( "self" ); + + if ( other == null ) + throw new IllegalArgumentException( "other" ); + + if ( self.length > other.length - offset ) + throw new IllegalArgumentException( "self and other lengths do not match" ); + + if ( inPlace ) + { + for ( int i = 0; i < self.length; i++ ) + { + self[i] = (byte)( self[i] ^ other[offset + i] ); + } + + return self; + } + else + { + byte[] result = new byte[self.length]; + + for ( int i = 0; i < self.length; i++ ) + { + result[i] = (byte)( self[i] ^ other[offset + i] ); + } + + return result; + } + } + + public static byte[] take( byte[] self, int count ) + { + return ByteExtensions.take( self, 0, count ); + } + + + /** + * Takes the first count bytes from the source and + * returns a new array containing those bytes. + * + * @param self The source of the bytes. + * @param offset The starting offset. + * @param count The number of bytes to take. + * @return count bytes from the source as a new array. + */ + public static byte[] take( byte[] self, int offset, int count ) + { + if ( self == null ) + throw new IllegalArgumentException( "self" ); + + if ( offset < 0 ) + throw new IllegalArgumentException( "offset cannot be < 0" ); + + if ( count <= 0 ) + throw new IllegalArgumentException( "count cannot be <= 0" ); + + if ( offset + count > self.length ) + throw new IllegalArgumentException( "offset + count cannot be > self.Length" ); + + byte[] result = new byte[count]; + + System.arraycopy( self, offset, result, 0, count ); + + return result; + } + + public static void zero( byte[] self ) + { + if ( self == null ) + throw new IllegalArgumentException( "self" ); + + for ( int i = 0; i < self.length; i++ ) { + self[i] = 0; + } + } +} diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java index 527b704d6db20..4d36c332b3beb 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java @@ -1,25 +1,21 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; +/** + * Abstract base class for all encryption algorithms. + * + */ public abstract class EncryptionAlgorithm extends Algorithm { + /** + * Constructor. + * @param name The name of the algorithm. + */ protected EncryptionAlgorithm(String name) { super(name); } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java index 8145964666abf..113a14404cf4d 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java index 3e1c725b3f8b0..4787a9d11a0f4 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; @@ -24,7 +12,23 @@ import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; +/** + * Defines the basic operations of cryptographic transformations. + * + */ public 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. + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + */ public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException; } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java index fdc15bc1dad94..e0028d51a5073 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; @@ -25,25 +13,140 @@ import javax.crypto.NoSuchPaddingException; +/** + * Abstract base class for all key wrap algorithms. + * + */ public abstract class KeyWrapAlgorithm extends Algorithm { + /** + * Constructor. + * + * @param name The name of the algorithm. + */ protected KeyWrapAlgorithm(String name) { super(name); } + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for encryption. + * Uses the default AES-KW initialization vector. + * @param key + * The AES key material to be used. + * @return A {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateEncryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateEncryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for decryption. + * Uses the default AES-KW initialization vector. + * @param key + * The AES key material to be used. + * @return A {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateDecryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateDecryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException; } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java index f0d8f2b953f88..53d7459b91363 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java index c6cf7244a1532..a1ead94749e65 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java index 4834485c31957..7c6e586fc09f8 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; @@ -25,18 +13,91 @@ import javax.crypto.NoSuchPaddingException; +/** + * Abstract base class for all symmetric encryption algorithms. + * + */ public abstract class SymmetricEncryptionAlgorithm extends EncryptionAlgorithm { + /** + * Constructor. + * + * @param name The name of the algorithm. + */ protected SymmetricEncryptionAlgorithm(String name) { super(name); } - public abstract ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; - - public abstract ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; - + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 authenticationData + * The authentication data to be used with authenticating encryption algorithms (optional) + * @return A {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 authenticationData + * The authentication data to be used with authenticating encryption algorithms (optional) + * @param provider + * The provider to use. + * @return A {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + */ public abstract ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 authenticationData + * The authentication data to be used with authenticating encryption algorithms (optional) + * @return A {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + */ + public abstract ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; + + /** + * Creates a {@link com.microsoft.azure.keyvault.cryptography.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 authenticationData + * The authentication data to be used with authenticating encryption algorithms (optional) + * @param provider + * The provider to use. + * @return A {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + */ + public abstract ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; + } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java index f9900d592b3de..14e0797b46587 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java index c0a5630e8df6b..14cf40023b7c8 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; @@ -25,6 +13,7 @@ import javax.crypto.NoSuchPaddingException; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public class Aes128Cbc extends AesCbc { @@ -44,7 +33,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); } @Override @@ -54,7 +43,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } @Override @@ -64,7 +53,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); } @Override @@ -74,6 +63,6 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java index eeb40fa3808b4..9e75131a3de84 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java index 96b03caf970e0..4ec8451b47901 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; @@ -25,6 +13,7 @@ import javax.crypto.NoSuchPaddingException; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public class Aes192Cbc extends AesCbc { @@ -44,7 +33,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); } @Override @@ -54,7 +43,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } @Override @@ -64,7 +53,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); } @Override @@ -74,7 +63,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java index 0e0e6758558a8..74f279eff8c72 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java index 88abe788ee757..629b647ec6b92 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; @@ -25,6 +13,7 @@ import javax.crypto.NoSuchPaddingException; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public class Aes256Cbc extends AesCbc { @@ -44,7 +33,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); } @Override @@ -54,7 +43,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcEncryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } @Override @@ -64,7 +53,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, null); + return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); } @Override @@ -74,7 +63,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authentica throw new InvalidKeyException("key must be at least 128 bits in length"); } - return new AesCbcDecryptor(AesCbc.Take(KeySizeInBytes, key), iv, provider); + return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java index 495bc7bd69468..e038c808fec53 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java index 7c49fba06c6b2..49edaa57a71b5 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java index 882a21284d616..c2ccc2a88ab13 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java index 8f7fa07ae6f12..6bd7dfc28c639 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java index 2044f10895867..3c628688ef236 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; @@ -25,6 +13,7 @@ import javax.crypto.NoSuchPaddingException; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public final class AesKw128 extends AesKw { @@ -48,7 +37,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 128 bits long"); } - return super.CreateEncryptor(Take(KeySizeInBytes,key), iv, provider); + return super.CreateEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } @Override @@ -62,7 +51,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 128 bits long"); } - return super.CreateDecryptor(Take(KeySizeInBytes,key), iv, provider); + return super.CreateDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java index bb652553ff83e..dd24b0011a0c1 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; @@ -25,6 +13,7 @@ import javax.crypto.NoSuchPaddingException; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public final class AesKw192 extends AesKw { @@ -48,7 +37,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 192 bits long"); } - return super.CreateEncryptor(Take(KeySizeInBytes,key), iv, provider); + return super.CreateEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } @Override @@ -62,7 +51,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 192 bits long"); } - return super.CreateDecryptor(Take(KeySizeInBytes,key), iv, provider); + return super.CreateDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java index b2ed7dd4815f7..79398e292adc4 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; @@ -25,6 +13,7 @@ import javax.crypto.NoSuchPaddingException; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public final class AesKw256 extends AesKw { @@ -48,7 +37,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 256 bits long"); } - return super.CreateEncryptor(Take(KeySizeInBytes,key), iv, provider); + return super.CreateEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } @Override @@ -62,7 +51,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 256 bits long"); } - return super.CreateDecryptor(Take(KeySizeInBytes,key), iv, provider); + return super.CreateDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java index 8161095756f88..4770183bb3ab8 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java index dd673f61ab416..83343057aa55a 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java index 424778e85f261..55b57b6acd633 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java new file mode 100644 index 0000000000000..f3101db3f04c0 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// + +/** + * This package contains cryptographic functions and implementations. + */ +package com.microsoft.azure.keyvault.cryptography.algorithms; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package.html b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package.html deleted file mode 100644 index 102a782ab4a86..0000000000000 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the Azure Key Vault Extension Cryptographic algorithm classes. - - diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java new file mode 100644 index 0000000000000..5492e8c677615 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// + +/** + * This package contains cryptographic functions and implementations + * of RSA and symmetric keys that conform with the IKey interface. + */ +package com.microsoft.azure.keyvault.cryptography; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package.html b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package.html deleted file mode 100644 index 12edd05fd0bac..0000000000000 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the Azure Key Vault Extension classes. - - diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java index 6498b9508dff6..c35cfcdfc6c24 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java @@ -12,6 +12,7 @@ import org.junit.Test; import com.microsoft.azure.keyvault.cryptography.Algorithm; +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; @@ -63,7 +64,7 @@ public void testAes128CbcOneBlock() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(16,encrypted),ED); + assertArrayEquals(ByteExtensions.take(encrypted, 16), ED); } catch (Exception e) { fail(e.getMessage()); } @@ -81,7 +82,7 @@ public void testAes128CbcOneBlock() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(16, decrypted), PLAIN); + assertArrayEquals(ByteExtensions.take(decrypted, 16), PLAIN); } catch (Exception e) { fail(e.getMessage()); } @@ -110,7 +111,7 @@ public void testAes128CbcTwoBlock() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(32,encrypted),ED); + assertArrayEquals(ByteExtensions.take(encrypted, 32), ED); } catch (Exception e) { fail(e.getMessage()); } @@ -128,7 +129,7 @@ public void testAes128CbcTwoBlock() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(32, decrypted), PLAIN); + assertArrayEquals(ByteExtensions.take(decrypted, 32), PLAIN); } catch (Exception e) { fail(e.getMessage()); } @@ -157,7 +158,7 @@ public void testAes128CbcOneBlock_ExcessKeyMaterial() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(16,encrypted),ED); + assertArrayEquals(ByteExtensions.take(encrypted, 16),ED); } catch (Exception e) { fail(e.getMessage()); } @@ -175,7 +176,7 @@ public void testAes128CbcOneBlock_ExcessKeyMaterial() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(16, decrypted), PLAIN); + assertArrayEquals(ByteExtensions.take(decrypted, 16), PLAIN); } catch (Exception e) { fail(e.getMessage()); } @@ -204,7 +205,7 @@ public void testAes128CbcTwoBlock_ExcessKeyMaterial() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(32,encrypted),ED); + assertArrayEquals(ByteExtensions.take(encrypted, 32), ED); } catch (Exception e) { fail(e.getMessage()); } @@ -222,7 +223,7 @@ public void testAes128CbcTwoBlock_ExcessKeyMaterial() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(Algorithm.Take(32, decrypted), PLAIN); + assertArrayEquals(ByteExtensions.take(decrypted, 32), PLAIN); } catch (Exception e) { fail(e.getMessage()); } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java index 334ad65b5f3d4..c78460edcfdec 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java index e902dad696565..ed88be41ab019 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java index 69b685c50ea40..6d50e9c6c049c 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java index b28d4464449e2..67dcd6f35b83e 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java index 1c1d45cab33d3..2aae9e82f23b3 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java @@ -1,7 +1,7 @@ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for - * license information. + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java index 290a07c94003e..e026b82b7d9ae 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java index 60d3d927bcdee..c2564685eb822 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java index 7f0a1fbd287d0..07cd0a8dc49b7 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.authentication; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java index ad1a3e8206271..9c184cb7cea5b 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.authentication; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java index de8a167ee8eda..44eb04f681b56 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.test; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java index 18a13e9423e9b..3af77cfca2625 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.test; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java index 219b2202eade1..54eb89cd3d444 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.test; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java index 2ebb0c791a977..d3deb5fcb23f5 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.test; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java index 1673ded8ff130..af27ec8973c2f 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.test; From cd1f4c1852ea6fcd6348c9d5b92841afb5246885 Mon Sep 17 00:00:00 2001 From: Hervey Wilson Date: Wed, 24 Aug 2016 15:22:19 -0700 Subject: [PATCH 08/14] Fix RSA256 signature --- .../cryptography/ISignatureTransform.java | 16 +++ .../azure/keyvault/cryptography/RsaKey.java | 24 ++--- .../cryptography/algorithms/Rs256.java | 102 ++++++------------ .../cryptography/algorithms/RsaSignature.java | 91 ++++++++-------- .../cryptography/test/AesCbcTest.java | 1 - .../cryptography/test/RsaKeyTest.java | 12 ++- 6 files changed, 112 insertions(+), 134 deletions(-) create mode 100644 azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java new file mode 100644 index 0000000000000..484b1448fb513 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java @@ -0,0 +1,16 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.cryptography; + +import java.security.GeneralSecurityException; + +public interface ISignatureTransform { + + public byte[] sign(final byte[] digest) throws GeneralSecurityException; + + public boolean verify(final byte[] digest, final byte[] signature) throws GeneralSecurityException; +} diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java index 4548a883c17fd..4abfcfd8855a6 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java @@ -1,19 +1,7 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography; @@ -262,7 +250,7 @@ public ListenableFuture> signAsync(final byte[] digest, fin Rs256 algo = (Rs256)baseAlgorithm; - Rs256.Rs256Signer signer = algo.createSigner(_keyPair); + ISignatureTransform signer = algo.createSignatureTransform(_keyPair); try { return Futures.immediateFuture(Pair.of(signer.sign(digest), Rs256.AlgorithmName)); @@ -292,10 +280,10 @@ public ListenableFuture verifyAsync(final byte[] digest, final byte[] s Rs256 algo = (Rs256)baseAlgorithm; - Rs256.Rs256Verifier signer = algo.createVerifier(_keyPair); + ISignatureTransform signer = algo.createSignatureTransform(_keyPair); try { - return Futures.immediateFuture(signer.verify(signature, digest)); + return Futures.immediateFuture(signer.verify(digest, signature)); } catch (Exception e) { return Futures.immediateFailedFuture(e); } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java index 750a02f529ea7..54a4fd4572361 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java @@ -1,32 +1,19 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; import java.math.BigInteger; -import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; +import com.microsoft.azure.keyvault.cryptography.ISignatureTransform; /** * @@ -35,27 +22,31 @@ public class Rs256 extends RsaSignature { static final String RsaNone = "RSA/ECB/PKCS1Padding"; - public class Rs256Signer { - + class Rs256SignatureTransform implements ISignatureTransform { + private final KeyPair _keyPair; private final int _emLen; - private final BigInteger _n; - - Rs256Signer(KeyPair keyPair) { - + Rs256SignatureTransform(KeyPair keyPair) { _keyPair = keyPair; - _n = ((RSAPublicKey)_keyPair.getPublic()).getModulus(); - _emLen = getOctetLength( _n.bitLength() ); + BigInteger modulus = ((RSAPublicKey)_keyPair.getPublic()).getModulus(); + + _emLen = getOctetLength( modulus.bitLength() ); + } - - public byte[] sign(final byte[] digest) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + + @Override + public byte[] sign(byte[] digest) throws NoSuchAlgorithmException { // Signing isn't just a case of encrypting the digest, there is much more to do. // For details of the algorithm, see https://tools.ietf.org/html/rfc3447#section-8.2 + if ( _keyPair.getPrivate() == null ) { + // TODO + } + // Construct the encoded message - byte[] EM = EMSA_PKCS1_V1_5_ENCODE(digest, _emLen, "SHA-256"); + byte[] EM = EMSA_PKCS1_V1_5_ENCODE_HASH(digest, _emLen, "SHA-256"); // Convert to integer message BigInteger s = OS2IP(EM); @@ -64,26 +55,14 @@ public byte[] sign(final byte[] digest) throws InvalidKeyException, NoSuchAlgori s = RSASP1((RSAPrivateKey)_keyPair.getPrivate(), s); // Convert to octet sequence - return I2OSP(s, getOctetLength( _n.bitLength() ) ); + return I2OSP(s, _emLen ); } - } - - public class Rs256Verifier { - - private final KeyPair _keyPair; - private final BigInteger _n; - private final int _emLength; - - Rs256Verifier(KeyPair keyPair) { - _keyPair = keyPair; - _n = ((RSAPublicKey)_keyPair.getPublic()).getModulus(); - _emLength = getOctetLength( _n.bitLength() ); - } - - public boolean verify(final byte[] signature, final byte[] digest) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + + @Override + public boolean verify(byte[] digest, byte[] signature) throws NoSuchAlgorithmException { - if ( signature.length != getOctetLength( _n.bitLength() ) ) { - throw new IllegalBlockSizeException(); + if ( signature.length != _emLen ) { + throw new IllegalArgumentException( "invalid signature length"); } // Convert to integer signature @@ -92,21 +71,13 @@ public boolean verify(final byte[] signature, final byte[] digest) throws Invali // Convert integer message BigInteger m = RSAVP1((RSAPublicKey)_keyPair.getPublic(), s); + byte[] EM = I2OSP(m, _emLen ); + byte[] EM2 = EMSA_PKCS1_V1_5_ENCODE_HASH(digest, _emLen, "SHA-256"); - byte[] EM = I2OSP(m, getOctetLength( _n.bitLength() ) ); - byte[] EM2 = EMSA_PKCS1_V1_5_ENCODE(digest, _emLength, "SHA-256"); - - // TODO: Need constant time compare - if ( EM.length != EM2.length ) - return false; - - for ( int i = 0; i < digest.length; i++ ) { - if ( EM[i] != EM2[i] ) - return false; - } - - return true; + // Use constant time compare + return ByteExtensions.sequenceEqualConstantTime(EM, EM2); } + } public final static String AlgorithmName = "RS256"; @@ -115,12 +86,9 @@ public Rs256() { super(AlgorithmName); } - public Rs256Signer createSigner(KeyPair keyPair) { + @Override + public ISignatureTransform createSignatureTransform(KeyPair keyPair) { - return new Rs256Signer(keyPair); - } - - public Rs256Verifier createVerifier(KeyPair keyPair) { - return new Rs256Verifier(keyPair); + return new Rs256SignatureTransform(keyPair); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java index a9ac4d4559cbb..e5248b47bfb52 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java @@ -1,24 +1,13 @@ /** - * - * Copyright (c) Microsoft and contributors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. */ package com.microsoft.azure.keyvault.cryptography.algorithms; import java.math.BigInteger; +import java.security.KeyPair; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; @@ -26,6 +15,7 @@ import java.util.Arrays; import com.microsoft.azure.keyvault.cryptography.AsymmetricSignatureAlgorithm; +import com.microsoft.azure.keyvault.cryptography.ISignatureTransform; import com.microsoft.azure.keyvault.cryptography.Strings; public abstract class RsaSignature extends AsymmetricSignatureAlgorithm { @@ -37,33 +27,10 @@ protected RsaSignature(String name) { super(name); } - protected 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; - } - - 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); - } - protected int getOctetLength(int bits) { return ( bits % 8 > 0 ) ? bits >> 3 + 1 : bits >> 3; } - /* * See https://tools.ietf.org/html/rfc3447#section-4.2 */ @@ -161,7 +128,6 @@ protected byte[] EMSA_PKCS1_V1_5_ENCODE(byte[] m, int emLen, String algorithm) t throw new IllegalArgumentException("m"); } - byte[] algorithmPrefix = null; MessageDigest messageDigest = null; // Check algorithm @@ -172,25 +138,55 @@ protected byte[] EMSA_PKCS1_V1_5_ENCODE(byte[] m, int emLen, String algorithm) t // Only supported algorithms if ( algorithm.equals("SHA-256") ) { - // Initialize prefix and digest - algorithmPrefix = sha256Prefix; + // Initialize digest messageDigest = MessageDigest.getInstance("SHA-256"); } else { throw new IllegalArgumentException("algorithm"); } - if ( algorithmPrefix == null || messageDigest == null ) { - throw new IllegalArgumentException("initialization with arguments failed"); - } - // Hash the message byte[] digest = messageDigest.digest(m); // Construct T, the DER encoded DigestInfo structure - byte[] T = new byte[algorithmPrefix.length + digest.length]; + return EMSA_PKCS1_V1_5_ENCODE_HASH(digest, emLen, algorithm); + } + + /* + * See https://tools.ietf.org/html/rfc3447#section-9.2 + */ + protected byte[] EMSA_PKCS1_V1_5_ENCODE_HASH(byte[] h, int emLen, String algorithm) throws NoSuchAlgorithmException { + + // Check m + if ( h == null || h.length == 0 ) { + throw new IllegalArgumentException("m"); + } + + byte[] algorithmPrefix = null; + + // Check algorithm + if ( Strings.isNullOrWhiteSpace(algorithm) ) { + throw new IllegalArgumentException("algorithm"); + } + + // Only supported algorithms + if ( algorithm.equals("SHA-256") ) { + + // Initialize prefix and digest + algorithmPrefix = sha256Prefix; + + if ( h.length != 32 ) { + throw new IllegalArgumentException("h is incorrect length for SHA-256"); + } + } else { + throw new IllegalArgumentException("algorithm"); + } + + + // Construct T, the DER encoded DigestInfo structure + byte[] T = new byte[algorithmPrefix.length + h.length]; System.arraycopy(algorithmPrefix, 0, T, 0, algorithmPrefix.length); - System.arraycopy(digest, 0, T, algorithmPrefix.length, digest.length); + System.arraycopy(h, 0, T, algorithmPrefix.length, h.length); if ( emLen < T.length + 11 ) { throw new IllegalArgumentException("intended encoded message length too short"); @@ -212,4 +208,5 @@ protected byte[] EMSA_PKCS1_V1_5_ENCODE(byte[] m, int emLen, String algorithm) t return EM; } + public abstract ISignatureTransform createSignatureTransform(KeyPair keyPair); } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java index c35cfcdfc6c24..351f22a1ce993 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java @@ -11,7 +11,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import com.microsoft.azure.keyvault.cryptography.Algorithm; import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java index 454752d7bac8b..2b181398ae859 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -25,7 +25,8 @@ public class RsaKeyTest { // A Content Encryption Key, or Message. This value is kept consistent with the .NET // unit test cases to enable cross platform testing. - static final byte[] CEK = { 4, (byte) 211, 31, (byte) 197, 84, (byte) 157, (byte) 252, (byte) 254, 11, 100, (byte) 157, (byte) 250, 63, (byte) 170, 106, (byte) 206, 107, 124, (byte) 212, 45, 111, 107, 9, (byte) 219, (byte) 200, (byte) 177, 0, (byte) 240, (byte) 143, (byte) 156, 44, (byte) 207 }; + static final 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 }; + static final String CrossPlatformHash = "qPrtarvzXBKksm5A9v6xnXNtkARcg7n5ox9jjTI+aBE="; static final String CrossPlatformSignature = "RaNc+8WcWxplS8I7ynJLSoLJKz+dgBvrZhIGH3VFlTTyzu7b9d+lpaV9IKhzCNBsgSysKhgL7EZwVCOTBZ4m6xvKSXqVFXYaBPyBTD7VoKPMYMW6ai5x6xV5XAMaZPfMkff3Deg/RXcc8xQ28FhYuUa8yly01GySY4Hk55anEvb2wBxSy1UGun/0LE1lYH3C3XEgSry4cEkJHDJl1hp+wB4J/noXOqn5ECGU+/4ehBJOyW1gtUH0/gRe8yXnDH0AXepHRyH8iBHLWlKX1r+1/OrMulqOoi82RZzJlTyEz9X+bsQhllqGF6n3hdLS6toH9o7wUtwYNqSx82JuQT6iMg=="; private Provider _provider = null; @@ -134,11 +135,20 @@ public void testSignVerify() throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(CEK); + byte[] crossPlatformHash = Base64.decodeBase64(CrossPlatformHash); + byte[] crossPlatformSignature = Base64.decodeBase64(CrossPlatformSignature); + + assertNotNull( hash ); + assertEquals( 32, hash.length ); + assertArrayEquals(hash, crossPlatformHash); + Pair signature = key.signAsync(hash, "RS256").get(); boolean result = key.verifyAsync(hash, signature.getLeft(), "RS256").get(); assertTrue(result); + //assertArrayEquals(crossPlatformSignature, signature.getLeft()); + // Now prove we can verify the cross platform signature result = key.verifyAsync(hash, Base64.decodeBase64(CrossPlatformSignature), "RS256").get(); From 03a24ce45096ea38846bf4be6f4a8a5992dcc63b Mon Sep 17 00:00:00 2001 From: Hervey Wilson Date: Mon, 29 Aug 2016 16:58:23 -0700 Subject: [PATCH 09/14] Minor signature code cleanup --- .../azure/keyvault/cryptography/algorithms/RsaSignature.java | 2 -- .../azure/keyvault/cryptography/test/RsaKeyTest.java | 5 +++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java index e5248b47bfb52..84d2257ae2175 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java @@ -12,8 +12,6 @@ import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; -import java.util.Arrays; - import com.microsoft.azure.keyvault.cryptography.AsymmetricSignatureAlgorithm; import com.microsoft.azure.keyvault.cryptography.ISignatureTransform; import com.microsoft.azure.keyvault.cryptography.Strings; diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java index 2b181398ae859..18cf7db616e18 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -138,6 +138,7 @@ public void testSignVerify() throws Exception { byte[] crossPlatformHash = Base64.decodeBase64(CrossPlatformHash); byte[] crossPlatformSignature = Base64.decodeBase64(CrossPlatformSignature); + // Check the hash assertNotNull( hash ); assertEquals( 32, hash.length ); assertArrayEquals(hash, crossPlatformHash); @@ -145,9 +146,9 @@ public void testSignVerify() throws Exception { Pair signature = key.signAsync(hash, "RS256").get(); boolean result = key.verifyAsync(hash, signature.getLeft(), "RS256").get(); + // Check the signature assertTrue(result); - - //assertArrayEquals(crossPlatformSignature, signature.getLeft()); + assertArrayEquals(crossPlatformSignature, signature.getLeft()); // Now prove we can verify the cross platform signature result = key.verifyAsync(hash, Base64.decodeBase64(CrossPlatformSignature), "RS256").get(); From 7a47049d60bbb5688296ccf269e7210c0f3281ce Mon Sep 17 00:00:00 2001 From: Pooneh Date: Fri, 2 Sep 2016 10:59:27 -0700 Subject: [PATCH 10/14] Adapting the observer model for Key Vault wrapped client, fixed build becaue incompatibility with runtime and instead of using constant string for JWK algorithms use static class representations --- .../keyvault/extensions/KeyVaultKey.java | 10 +- .../KeyVaultKeyResolverBCProviderTest.java | 3 +- ...eyVaultKeyResolverDefaultProviderTest.java | 3 +- .../azure/keyvault/webkey/JsonWebKey.java | 14 +- .../webkey/JsonWebKeyEncryptionAlgorithm.java | 62 +- .../keyvault/webkey/JsonWebKeyOperation.java | 94 +- .../webkey/JsonWebKeySignatureAlgorithm.java | 79 +- .../azure/keyvault/webkey/JsonWebKeyType.java | 79 +- .../azure/keyvault/KeyVaultClient.java | 83 +- .../azure/keyvault/KeyVaultClientImpl.java | 4982 ++++++++--------- .../models/CertificateIssuerItem.java | 2 +- .../CertificateIssuerSetParameters.java | 2 +- .../CertificateIssuerUpdateParameters.java | 5 +- .../CertificateOperationUpdateParameter.java | 2 +- .../azure/keyvault/models/IssuerBundle.java | 2 +- .../keyvault/models/IssuerReference.java | 3 +- .../azure/keyvault/models/KeyBundle.java | 5 +- .../keyvault/models/KeyCreateParameters.java | 17 +- .../azure/keyvault/models/KeyItem.java | 5 +- .../models/KeyOperationsParameters.java | 7 +- .../azure/keyvault/models/KeyProperties.java | 2 +- .../keyvault/models/KeySignParameters.java | 7 +- .../keyvault/models/KeyUpdateParameters.java | 7 +- .../keyvault/models/KeyVerifyParameters.java | 7 +- .../azure/keyvault/models/SecretBundle.java | 9 +- .../azure/keyvault/models/SecretItem.java | 5 +- .../models/X509CertificateProperties.java | 4 +- .../keyvault/requests/CreateKeyRequest.java | 25 +- .../keyvault/requests/ImportKeyRequest.java | 3 +- .../keyvault/requests/UpdateKeyRequest.java | 11 +- .../keyvault/test/AsyncOperationsTest.java | 11 +- .../test/CertificateOperationsTest.java | 12 +- .../keyvault/test/KeyOperationsTest.java | 66 +- .../keyvault/test/SecretOperationsTest.java | 15 +- 34 files changed, 2768 insertions(+), 2875 deletions(-) diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java index 2ef3291cfca3a..f4afd66b74aaa 100755 --- a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java @@ -30,6 +30,8 @@ import com.microsoft.azure.keyvault.core.IKey; import com.microsoft.azure.keyvault.cryptography.RsaKey; import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyOperationResult; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; @@ -96,7 +98,7 @@ protected KeyVaultKey(KeyVaultClient client, KeyBundle keyBundle) { if (key.kty().equals(JsonWebKeyType.RSA)) { // The private key is not available for KeyVault keys implementation = new RsaKey(key.kid(), key.toRSA(false)); - } else if (key.kty().equals(JsonWebKeyType.RSAHSM)) { + } else if (key.kty().equals(JsonWebKeyType.RSA_HSM)) { // The private key is not available for KeyVault keys implementation = new RsaKey(key.kid(), key.toRSA(false)); } @@ -169,7 +171,7 @@ public ListenableFuture decryptAsync(byte[] ciphertext, byte[] iv, byte[ ListenableFuture> futureCall = client.decryptAsync( implementation.getKid(), - algorithm, + new JsonWebKeyEncryptionAlgorithm(algorithm), ciphertext, null); return Futures.transform(futureCall, new DecryptResultTransform()); @@ -207,7 +209,7 @@ public ListenableFuture unwrapKeyAsync(byte[] ciphertext, String algorit ListenableFuture> futureCall = client.unwrapKeyAsync( implementation.getKid(), - algorithm, + new JsonWebKeyEncryptionAlgorithm(algorithm), ciphertext, null); return Futures.transform(futureCall, new DecryptResultTransform()); @@ -227,7 +229,7 @@ public ListenableFuture> signAsync(byte[] digest, String al ListenableFuture> futureCall = client.signAsync( implementation.getKid(), - algorithm, + new JsonWebKeySignatureAlgorithm(algorithm), digest, null); return Futures.transform(futureCall, new SignResultTransform(algorithm)); diff --git a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java index 58948e52d9bb2..f7f16bb09ca29 100755 --- a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java @@ -38,6 +38,7 @@ import com.microsoft.azure.keyvault.models.SecretBundle; import com.microsoft.azure.keyvault.requests.CreateKeyRequest; import com.microsoft.azure.keyvault.requests.SetSecretRequest; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; import com.microsoft.rest.ServiceResponse; public class KeyVaultKeyResolverBCProviderTest extends KeyVaultClientIntegrationTestBase { @@ -79,7 +80,7 @@ public void KeyVault_KeyVaultKeyResolver_Key() throws InterruptedException, Exec { try { // Create a key on a vault. - CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA").build(); + CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); ServiceResponse response = keyVaultClient.createKey(request); KeyBundle bundle = response != null ? response.getBody() : null; diff --git a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java index e6932d917cda1..63708e2b6a085 100755 --- a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java @@ -22,6 +22,7 @@ import com.microsoft.azure.keyvault.models.SecretBundle; import com.microsoft.azure.keyvault.requests.CreateKeyRequest; import com.microsoft.azure.keyvault.requests.SetSecretRequest; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; // //Copyright © Microsoft Corporation, All Rights Reserved @@ -79,7 +80,7 @@ public void KeyVault_KeyVaultKeyResolver_Key() throws InterruptedException, Exec { try { // Create a key on a vault. - CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA").build(); + CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); KeyBundle keyBundle = keyVaultClient.createKey(request).getBody(); try diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java index e6670116cf5e4..868cab9204858 100755 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java @@ -45,12 +45,12 @@ public class JsonWebKey { * Key type, usually RSA. Possible values include: 'EC', 'RSA', 'RSA-HSM', * 'oct'. */ - private String kty; + private JsonWebKeyType kty; /** * The keyOps property. */ - private List keyOps; + private List keyOps; /** * RSA modulus. @@ -130,7 +130,7 @@ public JsonWebKey withKid(String kid) { * @return the key type. */ @JsonProperty("kty") - public String kty() { + public JsonWebKeyType kty() { return this.kty; } @@ -140,7 +140,7 @@ public String kty() { * @param kty the key type * @return the JsonWebKey object itself. */ - public JsonWebKey withKty(String kty) { + public JsonWebKey withKty(JsonWebKeyType kty) { this.kty = kty; return this; } @@ -151,7 +151,7 @@ public JsonWebKey withKty(String kty) { * @return the key operations. */ @JsonProperty("key_ops") - public List keyOps() { + public List keyOps() { return this.keyOps; } @@ -161,7 +161,7 @@ public List keyOps() { * @param keyOps the key operations value to set * @return the JsonWebKey object itself. */ - public JsonWebKey withKeyOps(List keyOps) { + public JsonWebKey withKeyOps(List keyOps) { this.keyOps = keyOps; return this; } @@ -455,7 +455,7 @@ private PrivateKey getRSAPrivateKey(Provider provider) { * Verifies if the key is an RSA key. */ private void checkRSACompatible() { - if (!JsonWebKeyType.RSA.equals(kty()) && !JsonWebKeyType.RSAHSM.equals(kty())) { + if (!JsonWebKeyType.RSA.equals(kty()) && !JsonWebKeyType.RSA_HSM.equals(kty())) { throw new UnsupportedOperationException("Not an RSA key"); } } diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java index 8eb412e21e412..67e5e99dd08c2 100755 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java @@ -1,7 +1,7 @@ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for - * license information. + * license information. */ package com.microsoft.azure.keyvault.webkey; @@ -10,30 +10,58 @@ import java.util.Collections; import java.util.List; +import com.fasterxml.jackson.annotation.JsonValue; + /** - * Supported JsonWebKey Algorithms. + * Defines values for JsonWebKeyEncryptionAlgorithm. */ public final class JsonWebKeyEncryptionAlgorithm { + /** Static value RSA-OAEP for JsonWebKeyEncryptionAlgorithm. */ + public static final JsonWebKeyEncryptionAlgorithm RSA_OAEP = new JsonWebKeyEncryptionAlgorithm("RSA-OAEP"); - /** - * The 'RSA-OAEP' algorithm. - */ - public static final String RSAOAEP = "RSA-OAEP"; - - /** - * The 'RSA1_5' algorithm. - */ - public static final String RSA15 = "RSA1_5"; + /** Static value RSA1_5 for JsonWebKeyEncryptionAlgorithm. */ + public static final JsonWebKeyEncryptionAlgorithm RSA1_5 = new JsonWebKeyEncryptionAlgorithm("RSA1_5"); + + private String value; /** - * All the JWK encryption algorithms. + * Creates a custom value for JsonWebKeyEncryptionAlgorithm. + * @param value the custom value */ - public static final List ALL_ALGORITHMS = - Collections.unmodifiableList( - Arrays.asList(new String[] {RSA15, RSAOAEP})); + public JsonWebKeyEncryptionAlgorithm(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } - private JsonWebKeyEncryptionAlgorithm() { - // not instantiable + @Override + public int hashCode() { + return value.hashCode(); } + @Override + public boolean equals(Object obj) { + if (!(obj instanceof JsonWebKeyEncryptionAlgorithm)) { + return false; + } + if (obj == this) { + return true; + } + JsonWebKeyEncryptionAlgorithm rhs = (JsonWebKeyEncryptionAlgorithm) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } + + /** + * All the JWK encryption algorithms. + */ + public static final List ALL_ALGORITHMS = + Collections.unmodifiableList(Arrays.asList(RSA_OAEP, RSA1_5)); } diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java index aeacbc6655ace..9dbb9d30fce67 100755 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java @@ -1,7 +1,7 @@ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for - * license information. + * license information. */ package com.microsoft.azure.keyvault.webkey; @@ -10,50 +10,70 @@ import java.util.Collections; import java.util.List; +import com.fasterxml.jackson.annotation.JsonValue; + /** - * Supported JsonWebKey operations. + * Defines values for JsonWebKeyOperation. */ public final class JsonWebKeyOperation { + /** Static value encrypt for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation ENCRYPT = new JsonWebKeyOperation("encrypt"); - /** - * Encrypt operation. - */ - public static final String ENCRYPT = "encrypt"; - - /** - * Decrypt operation. - */ - public static final String DECRYPT = "decrypt"; - - /** - * Sign operation. - */ - public static final String SIGN = "sign"; - - /** - * Verify operation. - */ - public static final String VERIFY = "verify"; - - /** - * WrapKey operation. - */ - public static final String WRAP = "wrapKey"; - - /** - * UnwrapKey operation. - */ - public static final String UNWRAP = "unwrapKey"; + /** Static value decrypt for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation DECRYPT = new JsonWebKeyOperation("decrypt"); + + /** Static value sign for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation SIGN = new JsonWebKeyOperation("sign"); + + /** Static value verify for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation VERIFY = new JsonWebKeyOperation("verify"); + + /** Static value wrapKey for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation WRAP_KEY = new JsonWebKeyOperation("wrapKey"); + + /** Static value unwrapKey for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation UNWRAP_KEY = new JsonWebKeyOperation("unwrapKey"); + + private String value; /** - * All JWK operations. + * Creates a custom value for JsonWebKeyOperation. + * @param value the custom value */ - public static final List ALL_OPERATIONS = - Collections.unmodifiableList( - Arrays.asList(new String[] {ENCRYPT, DECRYPT, SIGN, VERIFY, WRAP, UNWRAP })); + public JsonWebKeyOperation(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } - private JsonWebKeyOperation() { - // not instantiable + @Override + public int hashCode() { + return value.hashCode(); } + @Override + public boolean equals(Object obj) { + if (!(obj instanceof JsonWebKeyOperation)) { + return false; + } + if (obj == this) { + return true; + } + JsonWebKeyOperation rhs = (JsonWebKeyOperation) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } + + /** + * All the JWK operations. + */ + public static final List ALL_OPERATIONS = + Collections.unmodifiableList(Arrays.asList(ENCRYPT, DECRYPT, SIGN, VERIFY, WRAP_KEY, UNWRAP_KEY)); } diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java index 0dc97946c274b..5e532c10cd297 100755 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java @@ -1,7 +1,7 @@ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for - * license information. + * license information. */ package com.microsoft.azure.keyvault.webkey; @@ -10,39 +10,64 @@ import java.util.Collections; import java.util.List; +import com.fasterxml.jackson.annotation.JsonValue; + /** - * Supported JsonWebKey Algorithms. + * Defines values for JsonWebKeySignatureAlgorithm. */ public final class JsonWebKeySignatureAlgorithm { + /** Static value RS256 for JsonWebKeySignatureAlgorithm. */ + public static final JsonWebKeySignatureAlgorithm RS256 = new JsonWebKeySignatureAlgorithm("RS256"); - /** - * The 'RS256' algorithm. - */ - public static final String RS256 = "RS256"; - - /** - * The 'RS384' algorithm. - */ - public static final String RS384 = "RS384"; - - /** - * The 'RS512' algorithm. - */ - public static final String RS512 = "RS512"; - - /** - * The 'RSNULL' algorithm. - */ - public static final String RSNULL = "RSNULL"; + /** Static value RS384 for JsonWebKeySignatureAlgorithm. */ + public static final JsonWebKeySignatureAlgorithm RS384 = new JsonWebKeySignatureAlgorithm("RS384"); + + /** Static value RS512 for JsonWebKeySignatureAlgorithm. */ + public static final JsonWebKeySignatureAlgorithm RS512 = new JsonWebKeySignatureAlgorithm("RS512"); + + /** Static value RSNULL for JsonWebKeySignatureAlgorithm. */ + public static final JsonWebKeySignatureAlgorithm RSNULL = new JsonWebKeySignatureAlgorithm("RSNULL"); + + private String value; /** - * All JWK algorithms. + * Creates a custom value for JsonWebKeySignatureAlgorithm. + * @param value the custom value */ - public static final List ALL_ALGORITHMS = - Collections.unmodifiableList( - Arrays.asList(new String[] {RS256, RS384, RS512, RSNULL})); + public JsonWebKeySignatureAlgorithm(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } - private JsonWebKeySignatureAlgorithm() { - // not instantiable + @Override + public int hashCode() { + return value.hashCode(); } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof JsonWebKeySignatureAlgorithm)) { + return false; + } + if (obj == this) { + return true; + } + JsonWebKeySignatureAlgorithm rhs = (JsonWebKeySignatureAlgorithm) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } + + /** + * All the JWK signature algorithms. + */ + public static final List ALL_ALGORITHMS = + Collections.unmodifiableList(Arrays.asList(RS256, RS384, RS512, RSNULL)); } diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java index c5bdf89410d9e..8a7c9dbffbc8e 100755 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java @@ -1,7 +1,7 @@ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for - * license information. + * license information. */ package com.microsoft.azure.keyvault.webkey; @@ -10,39 +10,64 @@ import java.util.Collections; import java.util.List; +import com.fasterxml.jackson.annotation.JsonValue; + /** - * Supported JsonWebKey key types (kty). + * Defines values for JsonWebKeyType. */ public final class JsonWebKeyType { + /** Static value EC for JsonWebKeyType. */ + public static final JsonWebKeyType EC = new JsonWebKeyType("EC"); - /** - * The Elliptic Curve 'EC' key type. - */ - public static final String EC = "EC"; - - /** - * The 'RSA' key type. - */ - public static final String RSA = "RSA"; - - /** - * The 'RSA-HSM' key type. - */ - public static final String RSAHSM = "RSA-HSM"; - - /** - * The Octet 'oct' key type. - */ - public static final String OCT = "oct"; + /** Static value RSA for JsonWebKeyType. */ + public static final JsonWebKeyType RSA = new JsonWebKeyType("RSA"); + + /** Static value RSA-HSM for JsonWebKeyType. */ + public static final JsonWebKeyType RSA_HSM = new JsonWebKeyType("RSA-HSM"); + + /** Static value oct for JsonWebKeyType. */ + public static final JsonWebKeyType OCT = new JsonWebKeyType("oct"); + + private String value; /** - * All JWK key types. + * Creates a custom value for JsonWebKeyType. + * @param value the custom value */ - public static final List ALL_TYPES = - Collections.unmodifiableList( - Arrays.asList(new String[] {EC, RSA, RSAHSM, OCT})); + public JsonWebKeyType(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } - private JsonWebKeyType() { - // not instantiable + @Override + public int hashCode() { + return value.hashCode(); } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof JsonWebKeyType)) { + return false; + } + if (obj == this) { + return true; + } + JsonWebKeyType rhs = (JsonWebKeyType) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } + + /** + * All the JWK key types. + */ + public static final List ALL_TYPES = + Collections.unmodifiableList(Arrays.asList(EC, RSA, RSA_HSM, OCT)); } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java index 2aae9e82f23b3..0dbb76b43010b 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java @@ -41,11 +41,12 @@ import com.microsoft.azure.keyvault.requests.UpdateCertificateRequest; import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; import com.microsoft.azure.keyvault.requests.UpdateSecretRequest; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; import com.microsoft.azure.RestClient; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.credentials.ServiceClientCredentials; import okhttp3.ResponseBody; @@ -56,6 +57,8 @@ import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; +import rx.Observable; +import rx.functions.Func1; /** * Initializes a new instance of the KeyVaultClient class. @@ -179,7 +182,7 @@ private void initializeService() { interface KeyVaultClientService { @Headers({"Content-Type: application/json; charset=utf-8", "Accept: application/pkcs10"}) @GET("certificates/{certificate-name}/pending") - Call getPendingCertificateSigningRequest(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getPendingCertificateSigningRequest(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); } /** @@ -585,7 +588,7 @@ public ServiceCall restoreKeyAsync(String vaultBaseUrl, byte[] keyBun * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse encrypt(String keyIdentifier, String algorithm, byte[] value) + public ServiceResponse encrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.encrypt(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -600,7 +603,7 @@ public ServiceResponse encrypt(String keyIdentifier, String * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall encryptAsync(String keyIdentifier, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall encryptAsync(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.encryptAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value, serviceCallback); } @@ -616,7 +619,7 @@ public ServiceCall encryptAsync(String keyIdentifier, String * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse decrypt(String keyIdentifier, String algorithm, byte[] value) + public ServiceResponse decrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.decrypt(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -631,7 +634,7 @@ public ServiceResponse decrypt(String keyIdentifier, String * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall decryptAsync(String keyIdentifier, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall decryptAsync(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.decryptAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value, serviceCallback); } @@ -647,7 +650,7 @@ public ServiceCall decryptAsync(String keyIdentifier, String * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse sign(String keyIdentifier, String algorithm, byte[] value) + public ServiceResponse sign(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.sign(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -662,7 +665,7 @@ public ServiceResponse sign(String keyIdentifier, String alg * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall signAsync(String keyIdentifier, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall signAsync(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.signAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value, serviceCallback); } @@ -679,7 +682,7 @@ public ServiceCall signAsync(String keyIdentifier, String al * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyVerifyResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse verify(String keyIdentifier, String algorithm, byte[] digest, byte[] signature) + public ServiceResponse verify(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.verify(id.vault, id.name, id.version == null ? "" : id.version, algorithm, digest, signature); @@ -695,7 +698,7 @@ public ServiceResponse verify(String keyIdentifier, String algo * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall verifyAsync(String keyIdentifier, String algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { + public ServiceCall verifyAsync(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.verifyAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, digest, signature, serviceCallback); } @@ -711,7 +714,7 @@ public ServiceCall verifyAsync(String keyIdentifier, String alg * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse wrapKey(String keyIdentifier, String algorithm, byte[] value) + public ServiceResponse wrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.wrapKey(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -726,7 +729,7 @@ public ServiceResponse wrapKey(String keyIdentifier, String * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall wrapKeyAsync(String keyIdentifier, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall wrapKeyAsync(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.wrapKeyAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value, serviceCallback); } @@ -742,7 +745,7 @@ public ServiceCall wrapKeyAsync(String keyIdentifier, String * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse unwrapKey(String keyIdentifier, String algorithm, byte[] value) + public ServiceResponse unwrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.unwrapKey(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -757,7 +760,7 @@ public ServiceResponse unwrapKey(String keyIdentifier, Strin * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ - public ServiceCall unwrapKeyAsync(String keyIdentifier, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall unwrapKeyAsync(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.unwrapKeyAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value, serviceCallback); } @@ -1857,19 +1860,7 @@ public ServiceCall mergeCertificateAsync(MergeCertificateRequ */ public ServiceResponse getPendingCertificateSigningRequest(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getPendingCertificateSigningRequest(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - Response response = call.execute(); - return new ServiceResponse(response.body().string(), response); + return getPendingCertificateSigningRequestAsync(vaultBaseUrl, certificateName).toBlocking().single(); } /** @@ -1881,6 +1872,17 @@ public ServiceResponse getPendingCertificateSigningRequest(String vaultB * @return the {@link ServiceCall} object */ public ServiceCall getPendingCertificateSigningRequestAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(getPendingCertificateSigningRequestAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Gets the pending certificate signing request response. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the String object + */ + private Observable> getPendingCertificateSigningRequestAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1891,24 +1893,17 @@ public ServiceCall getPendingCertificateSigningRequestAsync(String vault throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getPendingCertificateSigningRequest(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - if (serviceCallback != null) { - serviceCallback.success(new ServiceResponse(response.body().string(), response)); - } - serviceCall.success(new ServiceResponse(response.body().string(), response)); - } catch (IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getPendingCertificateSigningRequest(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = new ServiceResponse(response.body().string(), response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java index 4c9e596423269..156945410742d 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java @@ -13,6 +13,7 @@ import com.google.common.base.Joiner; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceCall; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.AzureServiceResponseBuilder; import com.microsoft.azure.keyvault.models.BackupKeyResult; @@ -54,6 +55,10 @@ import com.microsoft.azure.keyvault.models.SecretSetParameters; import com.microsoft.azure.keyvault.models.SecretUpdateParameters; import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; import com.microsoft.azure.keyvault.webkey.Base64UrlJsonSerializer; import com.microsoft.azure.keyvault.webkey.Base64UrlJsonDeserializer; import com.microsoft.azure.ListOperationCallback; @@ -61,16 +66,15 @@ import com.microsoft.azure.PagedList; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestException; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; -import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; @@ -83,6 +87,8 @@ import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; /** * Initializes a new instance of the KeyVaultClientImpl class. @@ -246,199 +252,199 @@ private void initializeService() { interface KeyVaultClientService { @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/create") - Call createKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyCreateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> createKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyCreateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PUT("keys/{key-name}") - Call importKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyImportParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> importKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyImportParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "keys/{key-name}", method = "DELETE", hasBody = true) - Call deleteKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> deleteKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("keys/{key-name}/{key-version}") - Call updateKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyUpdateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> updateKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyUpdateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("keys/{key-name}/{key-version}") - Call getKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("keys/{key-name}/versions") - Call getKeyVersions(@Path("key-name") String keyName, @Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getKeyVersions(@Path("key-name") String keyName, @Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("keys") - Call getKeys(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getKeys(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/backup") - Call backupKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> backupKey(@Path("key-name") String keyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/restore") - Call restoreKey(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyRestoreParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> restoreKey(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyRestoreParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/{key-version}/encrypt") - Call encrypt(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> encrypt(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/{key-version}/decrypt") - Call decrypt(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> decrypt(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/{key-version}/sign") - Call sign(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeySignParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> sign(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeySignParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/{key-version}/verify") - Call verify(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyVerifyParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> verify(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyVerifyParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/{key-version}/wrapkey") - Call wrapKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> wrapKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("keys/{key-name}/{key-version}/unwrapkey") - Call unwrapKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> unwrapKey(@Path("key-name") String keyName, @Path("key-version") String keyVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyOperationsParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PUT("secrets/{secret-name}") - Call setSecret(@Path("secret-name") String secretName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SecretSetParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> setSecret(@Path("secret-name") String secretName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SecretSetParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "secrets/{secret-name}", method = "DELETE", hasBody = true) - Call deleteSecret(@Path("secret-name") String secretName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> deleteSecret(@Path("secret-name") String secretName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("secrets/{secret-name}/{secret-version}") - Call updateSecret(@Path("secret-name") String secretName, @Path("secret-version") String secretVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SecretUpdateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> updateSecret(@Path("secret-name") String secretName, @Path("secret-version") String secretVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SecretUpdateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("secrets/{secret-name}/{secret-version}") - Call getSecret(@Path("secret-name") String secretName, @Path("secret-version") String secretVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getSecret(@Path("secret-name") String secretName, @Path("secret-version") String secretVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("secrets") - Call getSecrets(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getSecrets(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("secrets/{secret-name}/versions") - Call getSecretVersions(@Path("secret-name") String secretName, @Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getSecretVersions(@Path("secret-name") String secretName, @Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates") - Call getCertificates(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificates(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "certificates/{certificate-name}", method = "DELETE", hasBody = true) - Call deleteCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> deleteCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PUT("certificates/contacts") - Call setCertificateContacts(@Body Contacts contacts, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> setCertificateContacts(@Body Contacts contacts, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/contacts") - Call getCertificateContacts(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificateContacts(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "certificates/contacts", method = "DELETE", hasBody = true) - Call deleteCertificateContacts(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> deleteCertificateContacts(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/issuers") - Call getCertificateIssuers(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificateIssuers(@Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PUT("certificates/issuers/{issuer-name}") - Call setCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateIssuerSetParameters parameter, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> setCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateIssuerSetParameters parameter, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("certificates/issuers/{issuer-name}") - Call updateCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateIssuerUpdateParameters parameter, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> updateCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateIssuerUpdateParameters parameter, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/issuers/{issuer-name}") - Call getCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "certificates/issuers/{issuer-name}", method = "DELETE", hasBody = true) - Call deleteCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> deleteCertificateIssuer(@Path("issuer-name") String issuerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("certificates/{certificate-name}/create") - Call createCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateCreateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> createCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateCreateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("certificates/{certificate-name}/import") - Call importCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateImportParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> importCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateImportParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/{certificate-name}/versions") - Call getCertificateVersions(@Path("certificate-name") String certificateName, @Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificateVersions(@Path("certificate-name") String certificateName, @Query("maxresults") Integer maxresults, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/{certificate-name}/policy") - Call getCertificatePolicy(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificatePolicy(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("certificates/{certificate-name}/policy") - Call updateCertificatePolicy(@Path("certificate-name") String certificateName, @Body CertificatePolicy certificatePolicy, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> updateCertificatePolicy(@Path("certificate-name") String certificateName, @Body CertificatePolicy certificatePolicy, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("certificates/{certificate-name}/{certificate-version}") - Call updateCertificate(@Path("certificate-name") String certificateName, @Path("certificate-version") String certificateVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateUpdateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> updateCertificate(@Path("certificate-name") String certificateName, @Path("certificate-version") String certificateVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateUpdateParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/{certificate-name}/{certificate-version}") - Call getCertificate(@Path("certificate-name") String certificateName, @Path("certificate-version") String certificateVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificate(@Path("certificate-name") String certificateName, @Path("certificate-version") String certificateVersion, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("certificates/{certificate-name}/pending") - Call updateCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateOperationUpdateParameter certificateOperation, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> updateCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateOperationUpdateParameter certificateOperation, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("certificates/{certificate-name}/pending") - Call getCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> getCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "certificates/{certificate-name}/pending", method = "DELETE", hasBody = true) - Call deleteCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> deleteCertificateOperation(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("certificates/{certificate-name}/pending/merge") - Call mergeCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateMergeParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); + Observable> mergeCertificate(@Path("certificate-name") String certificateName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CertificateMergeParameters parameters, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getKeyVersionsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getKeyVersionsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getKeysNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getKeysNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getSecretsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getSecretsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getSecretVersionsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getSecretVersionsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getCertificatesNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getCertificatesNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getCertificateIssuersNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getCertificateIssuersNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call getCertificateVersionsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getCertificateVersionsNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } @@ -447,38 +453,14 @@ interface KeyVaultClientService { * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse createKey(String vaultBaseUrl, String keyName, String kty) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (kty == null) { - throw new IllegalArgumentException("Parameter kty is required and cannot be null."); - } - final Integer keySize = null; - final List keyOps = null; - final KeyAttributes keyAttributes = null; - final Map tags = null; - KeyCreateParameters parameters = new KeyCreateParameters(); - parameters.withKty(kty); - parameters.withKeySize(null); - parameters.withKeyOps(null); - parameters.withKeyAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return createKeyDelegate(call.execute()); + public ServiceResponse createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createKeyAsync(vaultBaseUrl, keyName, kty).toBlocking().single(); } /** @@ -486,11 +468,23 @@ public ServiceResponse createKey(String vaultBaseUrl, String keyName, * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, final ServiceCallback serviceCallback) { + return ServiceCall.create(createKeyAsync(vaultBaseUrl, keyName, kty), serviceCallback); + } + + /** + * Creates a new, named, key in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @return the observable to the KeyBundle object */ - public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, String kty, final ServiceCallback serviceCallback) { + public Observable> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -504,7 +498,7 @@ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName throw new IllegalArgumentException("Parameter kty is required and cannot be null."); } final Integer keySize = null; - final List keyOps = null; + final List keyOps = null; final KeyAttributes keyAttributes = null; final Map tags = null; KeyCreateParameters parameters = new KeyCreateParameters(); @@ -514,26 +508,18 @@ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName parameters.withKeyAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = createKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -541,9 +527,9 @@ public void onResponse(Call call, Response response) * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' * @param keySize The key size in bytes. e.g. 1024 or 2048. - * @param keyOps the List<String> value + * @param keyOps the List<JsonWebKeyOperation> value * @param keyAttributes the KeyAttributes value * @param tags Application-specific metadata in the form of key-value pairs * @throws KeyVaultErrorException exception thrown from REST call @@ -551,31 +537,8 @@ public void onResponse(Call call, Response response) * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse createKey(String vaultBaseUrl, String keyName, String kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (kty == null) { - throw new IllegalArgumentException("Parameter kty is required and cannot be null."); - } - Validator.validate(keyOps); - Validator.validate(keyAttributes); - Validator.validate(tags); - KeyCreateParameters parameters = new KeyCreateParameters(); - parameters.withKty(kty); - parameters.withKeySize(keySize); - parameters.withKeyOps(keyOps); - parameters.withKeyAttributes(keyAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return createKeyDelegate(call.execute()); + public ServiceResponse createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createKeyAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags).toBlocking().single(); } /** @@ -583,15 +546,31 @@ public ServiceResponse createKey(String vaultBaseUrl, String keyName, * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' * @param keySize The key size in bytes. e.g. 1024 or 2048. - * @param keyOps the List<String> value + * @param keyOps the List<JsonWebKeyOperation> value * @param keyAttributes the KeyAttributes value * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(createKeyAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags), serviceCallback); + } + + /** + * Creates a new, named, key in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param keySize The key size in bytes. e.g. 1024 or 2048. + * @param keyOps the List<JsonWebKeyOperation> value + * @param keyAttributes the KeyAttributes value + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the KeyBundle object */ - public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, String kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + public Observable> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -614,26 +593,18 @@ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName parameters.withKeyAttributes(keyAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = createKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse createKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -655,30 +626,7 @@ private ServiceResponse createKeyDelegate(Response resp * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse importKey(String vaultBaseUrl, String keyName, JsonWebKey key) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (key == null) { - throw new IllegalArgumentException("Parameter key is required and cannot be null."); - } - Validator.validate(key); - final Boolean hsm = null; - final KeyAttributes keyAttributes = null; - final Map tags = null; - KeyImportParameters parameters = new KeyImportParameters(); - parameters.withHsm(null); - parameters.withKey(key); - parameters.withKeyAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return importKeyDelegate(call.execute()); + return importKeyAsync(vaultBaseUrl, keyName, key).toBlocking().single(); } /** @@ -688,9 +636,21 @@ public ServiceResponse importKey(String vaultBaseUrl, String keyName, * @param keyName The name of the key * @param key The Json web key * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, final ServiceCallback serviceCallback) { + return ServiceCall.create(importKeyAsync(vaultBaseUrl, keyName, key), serviceCallback); + } + + /** + * Imports a key into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param key The Json web key + * @return the observable to the KeyBundle object + */ + public Observable> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -713,26 +673,18 @@ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName parameters.withKeyAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = importKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.importKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = importKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -750,29 +702,7 @@ public void onResponse(Call call, Response response) * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse importKey(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (key == null) { - throw new IllegalArgumentException("Parameter key is required and cannot be null."); - } - Validator.validate(key); - Validator.validate(keyAttributes); - Validator.validate(tags); - KeyImportParameters parameters = new KeyImportParameters(); - parameters.withHsm(hsm); - parameters.withKey(key); - parameters.withKeyAttributes(keyAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return importKeyDelegate(call.execute()); + return importKeyAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags).toBlocking().single(); } /** @@ -785,9 +715,24 @@ public ServiceResponse importKey(String vaultBaseUrl, String keyName, * @param keyAttributes The key management attributes * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(importKeyAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags), serviceCallback); + } + + /** + * Imports a key into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @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 + * @return the observable to the KeyBundle object + */ + public Observable> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -800,7 +745,6 @@ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName if (key == null) { throw new IllegalArgumentException("Parameter key is required and cannot be null."); } - Validator.validate(key); Validator.validate(keyAttributes); Validator.validate(tags); KeyImportParameters parameters = new KeyImportParameters(); @@ -809,26 +753,18 @@ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName parameters.withKeyAttributes(keyAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = importKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.importKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = importKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse importKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -849,18 +785,7 @@ private ServiceResponse importKeyDelegate(Response resp * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse deleteKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteKey(keyName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return deleteKeyDelegate(call.execute()); + return deleteKeyAsync(vaultBaseUrl, keyName).toBlocking().single(); } /** @@ -869,9 +794,20 @@ public ServiceResponse deleteKey(String vaultBaseUrl, String keyName) * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall deleteKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteKeyAsync(vaultBaseUrl, keyName), serviceCallback); + } + + /** + * Deletes the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the observable to the KeyBundle object + */ + public Observable> deleteKeyAsync(String vaultBaseUrl, String keyName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -882,26 +818,18 @@ public ServiceCall deleteKeyAsync(String vaultBaseUrl, String keyName throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteKey(keyName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = deleteKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.deleteKey(keyName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -923,28 +851,7 @@ private ServiceResponse deleteKeyDelegate(Response resp * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse updateKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final List keyOps = null; - final KeyAttributes keyAttributes = null; - final Map tags = null; - KeyUpdateParameters parameters = new KeyUpdateParameters(); - parameters.withKeyOps(null); - parameters.withKeyAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return updateKeyDelegate(call.execute()); + return updateKeyAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single(); } /** @@ -954,9 +861,21 @@ public ServiceResponse updateKey(String vaultBaseUrl, String keyName, * @param keyName The name of the key * @param keyVersion The version of the key * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateKeyAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + } + + /** + * Updates the Key Attributes associated with the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @return the observable to the KeyBundle object + */ + public Observable> updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -969,7 +888,7 @@ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - final List keyOps = null; + final List keyOps = null; final KeyAttributes keyAttributes = null; final Map tags = null; KeyUpdateParameters parameters = new KeyUpdateParameters(); @@ -977,26 +896,18 @@ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName parameters.withKeyAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -1013,29 +924,8 @@ public void onResponse(Call call, Response response) * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - Validator.validate(keyOps); - Validator.validate(keyAttributes); - Validator.validate(tags); - KeyUpdateParameters parameters = new KeyUpdateParameters(); - parameters.withKeyOps(keyOps); - parameters.withKeyAttributes(keyAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return updateKeyDelegate(call.execute()); + public ServiceResponse updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateKeyAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).toBlocking().single(); } /** @@ -1048,9 +938,24 @@ public ServiceResponse updateKey(String vaultBaseUrl, String keyName, * @param keyAttributes the KeyAttributes value * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateKeyAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags), serviceCallback); + } + + /** + * Updates the Key Attributes associated with the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. + * @param keyAttributes the KeyAttributes value + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the KeyBundle object */ - public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + public Observable> updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1071,26 +976,18 @@ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName parameters.withKeyAttributes(keyAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1112,21 +1009,7 @@ private ServiceResponse updateKeyDelegate(Response resp * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getKeyDelegate(call.execute()); + return getKeyAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single(); } /** @@ -1136,9 +1019,21 @@ public ServiceResponse getKey(String vaultBaseUrl, String keyName, St * @param keyName The name of the key * @param keyVersion The version of the key * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(getKeyAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + } + + /** + * Retrieves the public portion of a key plus its attributes. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @return the observable to the KeyBundle object + */ + public Observable> getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1152,26 +1047,18 @@ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, S throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.getKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1192,26 +1079,14 @@ private ServiceResponse getKeyDelegate(Response respons * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeyVersions(keyName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getKeyVersionsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getKeyVersionsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1220,9 +1095,46 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorException * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the observable to the List<KeyItem> object + */ + public Observable>> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName) { + return getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getKeyVersionsSinglePageAsync(final String vaultBaseUrl, final String keyName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1234,32 +1146,18 @@ public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeyVersions(keyName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getKeyVersionsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getKeyVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getKeyVersions(keyName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getKeyVersionsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -1274,25 +1172,14 @@ public void onResponse(Call call, Response response) * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeyVersions(keyName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getKeyVersionsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getKeyVersionsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1302,9 +1189,48 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorException * @param keyName The name of the key * @param maxresults Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param maxresults Maximum number of results to return. + * @return the observable to the List<KeyItem> object + */ + public Observable>> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults) { + return getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of the specified key. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param keyName The name of the key + ServiceResponse> * @param maxresults Maximum number of results to return. + * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getKeyVersionsSinglePageAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1315,32 +1241,18 @@ public ServiceCall> getKeyVersionsAsync(final String vaultBaseUrl, throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeyVersions(keyName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getKeyVersionsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getKeyVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getKeyVersions(keyName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getKeyVersionsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getKeyVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1360,23 +1272,14 @@ private ServiceResponse> getKeyVersionsDelegate(Response> getKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeys(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getKeysDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getKeysNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1384,9 +1287,44 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorException * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getKeysAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getKeysSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the List<KeyItem> object + */ + public Observable>> getKeysAsync(final String vaultBaseUrl) { + return getKeysSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getKeysNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getKeysSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1395,32 +1333,18 @@ public ServiceCall> getKeysAsync(final String vaultBaseUrl, final } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeys(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getKeysDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getKeysNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getKeys(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getKeysDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -1434,22 +1358,14 @@ public void onResponse(Call call, Response response) * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeys(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getKeysDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getKeysNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1458,9 +1374,46 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorException * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param maxresults Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getKeysAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getKeysSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param maxresults Maximum number of results to return. + * @return the observable to the List<KeyItem> object + */ + public Observable>> getKeysAsync(final String vaultBaseUrl, final Integer maxresults) { + return getKeysSinglePageAsync(vaultBaseUrl, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getKeysNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List keys in the specified vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param maxresults Maximum number of results to return. + * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getKeysSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1468,32 +1421,18 @@ public ServiceCall> getKeysAsync(final String vaultBaseUrl, final throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getKeys(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getKeysDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getKeysNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getKeys(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getKeysDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getKeysDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1514,18 +1453,7 @@ private ServiceResponse> getKeysDelegate(Response backupKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.backupKey(keyName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return backupKeyDelegate(call.execute()); + return backupKeyAsync(vaultBaseUrl, keyName).toBlocking().single(); } /** @@ -1534,9 +1462,20 @@ public ServiceResponse backupKey(String vaultBaseUrl, String ke * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall backupKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return ServiceCall.create(backupKeyAsync(vaultBaseUrl, keyName), serviceCallback); + } + + /** + * Requests that a backup of the specified key be downloaded to the client. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the observable to the BackupKeyResult object + */ + public Observable> backupKeyAsync(String vaultBaseUrl, String keyName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1547,26 +1486,18 @@ public ServiceCall backupKeyAsync(String vaultBaseUrl, String k throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.backupKey(keyName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = backupKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.backupKey(keyName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = backupKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse backupKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1587,20 +1518,7 @@ private ServiceResponse backupKeyDelegate(Response restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (keyBundleBackup == null) { - throw new IllegalArgumentException("Parameter keyBundleBackup is required and cannot be null."); - } - KeyRestoreParameters parameters = new KeyRestoreParameters(); - parameters.withKeyBundleBackup(keyBundleBackup); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.restoreKey(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return restoreKeyDelegate(call.execute()); + return restoreKeyAsync(vaultBaseUrl, keyBundleBackup).toBlocking().single(); } /** @@ -1609,9 +1527,20 @@ public ServiceResponse restoreKey(String vaultBaseUrl, byte[] keyBund * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyBundleBackup the backup blob associated with a key bundle * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, final ServiceCallback serviceCallback) { + return ServiceCall.create(restoreKeyAsync(vaultBaseUrl, keyBundleBackup), serviceCallback); + } + + /** + * Restores the backup key in to a vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyBundleBackup the backup blob associated with a key bundle + * @return the observable to the KeyBundle object + */ + public Observable> restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1624,26 +1553,18 @@ public ServiceCall restoreKeyAsync(String vaultBaseUrl, byte[] keyBun KeyRestoreParameters parameters = new KeyRestoreParameters(); parameters.withKeyBundleBackup(keyBundleBackup); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.restoreKey(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = restoreKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.restoreKey(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = restoreKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse restoreKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1666,31 +1587,8 @@ private ServiceResponse restoreKeyDelegate(Response res * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse encrypt(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (algorithm == null) { - throw new IllegalArgumentException("Parameter algorithm is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.withAlgorithm(algorithm); - parameters.withValue(value); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.encrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return encryptDelegate(call.execute()); + public ServiceResponse encrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return encryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); } /** @@ -1702,9 +1600,23 @@ public ServiceResponse encrypt(String vaultBaseUrl, String k * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(encryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object */ - public ServiceCall encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public Observable> encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1727,26 +1639,18 @@ public ServiceCall encryptAsync(String vaultBaseUrl, String parameters.withAlgorithm(algorithm); parameters.withValue(value); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.encrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = encryptDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.encrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = encryptDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse encryptDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1769,31 +1673,8 @@ private ServiceResponse encryptDelegate(Response decrypt(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (algorithm == null) { - throw new IllegalArgumentException("Parameter algorithm is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.withAlgorithm(algorithm); - parameters.withValue(value); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.decrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return decryptDelegate(call.execute()); + public ServiceResponse decrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return decryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); } /** @@ -1805,9 +1686,23 @@ public ServiceResponse decrypt(String vaultBaseUrl, String k * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(decryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object */ - public ServiceCall decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public Observable> decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1830,26 +1725,18 @@ public ServiceCall decryptAsync(String vaultBaseUrl, String parameters.withAlgorithm(algorithm); parameters.withValue(value); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.decrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = decryptDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.decrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = decryptDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse decryptDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1872,7 +1759,36 @@ private ServiceResponse decryptDelegate(Response sign(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public ServiceResponse sign(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return signAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); + } + + /** + * Creates a signature from a digest using the specified key in the vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param value the Base64Url value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(signAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Creates a signature from a digest using the specified key in the vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1895,64 +1811,18 @@ public ServiceResponse sign(String vaultBaseUrl, String keyN parameters.withAlgorithm(algorithm); parameters.withValue(value); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.sign(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return signDelegate(call.execute()); - } - - /** - * Creates a signature from a digest using the specified key in the vault. - * - * @param vaultBaseUrl The vault name, e.g. 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. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' - * @param value the Base64Url value - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object - */ - public ServiceCall signAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (algorithm == null) { - throw new IllegalArgumentException("Parameter algorithm is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - KeySignParameters parameters = new KeySignParameters(); - parameters.withAlgorithm(algorithm); - parameters.withValue(value); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.sign(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = signDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); - } - } - }); - return serviceCall; + return service.sign(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = signDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); } private ServiceResponse signDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1976,35 +1846,8 @@ private ServiceResponse signDelegate(Response * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyVerifyResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse verify(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] digest, byte[] signature) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (algorithm == null) { - throw new IllegalArgumentException("Parameter algorithm is required and cannot be null."); - } - if (digest == null) { - throw new IllegalArgumentException("Parameter digest is required and cannot be null."); - } - if (signature == null) { - throw new IllegalArgumentException("Parameter signature is required and cannot be null."); - } - KeyVerifyParameters parameters = new KeyVerifyParameters(); - parameters.withAlgorithm(algorithm); - parameters.withDigest(digest); - parameters.withSignature(signature); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.verify(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return verifyDelegate(call.execute()); + public ServiceResponse verify(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return verifyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).toBlocking().single(); } /** @@ -2017,9 +1860,24 @@ public ServiceResponse verify(String vaultBaseUrl, String keyNa * @param digest The digest used for signing * @param signature The signature to be verified * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { + public ServiceCall verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { + return ServiceCall.create(verifyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature), serviceCallback); + } + + /** + * Verifies a signature using the specified key. + * + * @param vaultBaseUrl The vault name, e.g. 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. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param digest The digest used for signing + * @param signature The signature to be verified + * @return the observable to the KeyVerifyResult object + */ + public Observable> verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2046,26 +1904,18 @@ public ServiceCall verifyAsync(String vaultBaseUrl, String keyN parameters.withDigest(digest); parameters.withSignature(signature); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.verify(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = verifyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.verify(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = verifyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse verifyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2088,31 +1938,8 @@ private ServiceResponse verifyDelegate(Response r * @throws IllegalArgumentException exception thrown from invalid parameters * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse wrapKey(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (algorithm == null) { - throw new IllegalArgumentException("Parameter algorithm is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.withAlgorithm(algorithm); - parameters.withValue(value); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.wrapKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return wrapKeyDelegate(call.execute()); + public ServiceResponse wrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return wrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); } /** @@ -2124,9 +1951,23 @@ public ServiceResponse wrapKey(String vaultBaseUrl, String k * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(wrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Wraps a symmetric key using the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object */ - public ServiceCall wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public Observable> wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2149,26 +1990,18 @@ public ServiceCall wrapKeyAsync(String vaultBaseUrl, String parameters.withAlgorithm(algorithm); parameters.withValue(value); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.wrapKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = wrapKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.wrapKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = wrapKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse wrapKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2191,31 +2024,8 @@ private ServiceResponse wrapKeyDelegate(Response unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (keyName == null) { - throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); - } - if (keyVersion == null) { - throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (algorithm == null) { - throw new IllegalArgumentException("Parameter algorithm is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.withAlgorithm(algorithm); - parameters.withValue(value); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.unwrapKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return unwrapKeyDelegate(call.execute()); + public ServiceResponse unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return unwrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); } /** @@ -2227,9 +2037,23 @@ public ServiceResponse unwrapKey(String vaultBaseUrl, String * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' * @param value the Base64Url value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(unwrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Unwraps a symmetric key using the specified key in the vault that has initially been used for wrapping the key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2252,26 +2076,18 @@ public ServiceCall unwrapKeyAsync(String vaultBaseUrl, Strin parameters.withAlgorithm(algorithm); parameters.withValue(value); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.unwrapKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = unwrapKeyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.unwrapKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = unwrapKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse unwrapKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2293,29 +2109,7 @@ private ServiceResponse unwrapKeyDelegate(Response setSecret(String vaultBaseUrl, String secretName, String value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - final Map tags = null; - final String contentType = null; - final SecretAttributes secretAttributes = null; - SecretSetParameters parameters = new SecretSetParameters(); - parameters.withValue(value); - parameters.withTags(null); - parameters.withContentType(null); - parameters.withSecretAttributes(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return setSecretDelegate(call.execute()); + return setSecretAsync(vaultBaseUrl, secretName, value).toBlocking().single(); } /** @@ -2325,9 +2119,21 @@ public ServiceResponse setSecret(String vaultBaseUrl, String secre * @param secretName The name of the secret in the given vault * @param value The value of the secret * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall setSecretAsync(String vaultBaseUrl, String secretName, String value, final ServiceCallback serviceCallback) { + return ServiceCall.create(setSecretAsync(vaultBaseUrl, secretName, value), serviceCallback); + } + + /** + * Sets a secret in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param value The value of the secret + * @return the observable to the SecretBundle object + */ + public Observable> setSecretAsync(String vaultBaseUrl, String secretName, String value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2349,26 +2155,18 @@ public ServiceCall setSecretAsync(String vaultBaseUrl, String secr parameters.withContentType(null); parameters.withSecretAttributes(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = setSecretDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = setSecretDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -2386,28 +2184,7 @@ public void onResponse(Call call, Response response) * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse setSecret(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (value == null) { - throw new IllegalArgumentException("Parameter value is required and cannot be null."); - } - Validator.validate(tags); - Validator.validate(secretAttributes); - SecretSetParameters parameters = new SecretSetParameters(); - parameters.withValue(value); - parameters.withTags(tags); - parameters.withContentType(contentType); - parameters.withSecretAttributes(secretAttributes); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return setSecretDelegate(call.execute()); + return setSecretAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes).toBlocking().single(); } /** @@ -2420,9 +2197,24 @@ public ServiceResponse setSecret(String vaultBaseUrl, String secre * @param contentType Type of the secret value such as a password * @param secretAttributes The secret management attributes * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall setSecretAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes, final ServiceCallback serviceCallback) { + return ServiceCall.create(setSecretAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes), serviceCallback); + } + + /** + * Sets a secret in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @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 + * @return the observable to the SecretBundle object + */ + public Observable> setSecretAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2443,26 +2235,18 @@ public ServiceCall setSecretAsync(String vaultBaseUrl, String secr parameters.withContentType(contentType); parameters.withSecretAttributes(secretAttributes); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = setSecretDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = setSecretDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse setSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2483,18 +2267,7 @@ private ServiceResponse setSecretDelegate(Response r * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse deleteSecret(String vaultBaseUrl, String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return deleteSecretDelegate(call.execute()); + return deleteSecretAsync(vaultBaseUrl, secretName).toBlocking().single(); } /** @@ -2503,9 +2276,20 @@ public ServiceResponse deleteSecret(String vaultBaseUrl, String se * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall deleteSecretAsync(String vaultBaseUrl, String secretName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteSecretAsync(vaultBaseUrl, secretName), serviceCallback); + } + + /** + * Deletes a secret from the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @return the observable to the SecretBundle object + */ + public Observable> deleteSecretAsync(String vaultBaseUrl, String secretName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2516,26 +2300,18 @@ public ServiceCall deleteSecretAsync(String vaultBaseUrl, String s throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = deleteSecretDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.deleteSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteSecretDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2557,28 +2333,7 @@ private ServiceResponse deleteSecretDelegate(Response updateSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (secretVersion == null) { - throw new IllegalArgumentException("Parameter secretVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final String contentType = null; - final SecretAttributes secretAttributes = null; - final Map tags = null; - SecretUpdateParameters parameters = new SecretUpdateParameters(); - parameters.withContentType(null); - parameters.withSecretAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return updateSecretDelegate(call.execute()); + return updateSecretAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single(); } /** @@ -2588,9 +2343,21 @@ public ServiceResponse updateSecret(String vaultBaseUrl, String se * @param secretName The name of the secret in the given vault * @param secretVersion The version of the secret * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateSecretAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); + } + + /** + * Updates the attributes associated with the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param secretVersion The version of the secret + * @return the observable to the SecretBundle object + */ + public Observable> updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2611,26 +2378,18 @@ public ServiceCall updateSecretAsync(String vaultBaseUrl, String s parameters.withSecretAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateSecretDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.updateSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateSecretDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -2648,27 +2407,7 @@ public void onResponse(Call call, Response response) * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse updateSecret(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (secretVersion == null) { - throw new IllegalArgumentException("Parameter secretVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - Validator.validate(secretAttributes); - Validator.validate(tags); - SecretUpdateParameters parameters = new SecretUpdateParameters(); - parameters.withContentType(contentType); - parameters.withSecretAttributes(secretAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return updateSecretDelegate(call.execute()); + return updateSecretAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags).toBlocking().single(); } /** @@ -2681,9 +2420,24 @@ public ServiceResponse updateSecret(String vaultBaseUrl, String se * @param secretAttributes The secret management attributes * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateSecretAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags), serviceCallback); + } + + /** + * Updates the attributes associated with the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param secretVersion The version of the secret + * @param contentType Type of the secret value such as a password + * @param secretAttributes The secret management attributes + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the SecretBundle object + */ + public Observable> updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2703,26 +2457,18 @@ public ServiceCall updateSecretAsync(String vaultBaseUrl, String s parameters.withSecretAttributes(secretAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateSecretDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.updateSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateSecretDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2744,21 +2490,7 @@ private ServiceResponse updateSecretDelegate(Response getSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (secretVersion == null) { - throw new IllegalArgumentException("Parameter secretVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getSecretDelegate(call.execute()); + return getSecretAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single(); } /** @@ -2768,9 +2500,21 @@ public ServiceResponse getSecret(String vaultBaseUrl, String secre * @param secretName The name of the secret in the given vault * @param secretVersion The version of the secret * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(getSecretAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); + } + + /** + * Gets a secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param secretVersion The version of the secret + * @return the observable to the SecretBundle object + */ + public Observable> getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2784,26 +2528,18 @@ public ServiceCall getSecretAsync(String vaultBaseUrl, String secr throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getSecretDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getSecret(secretName, secretVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getSecretDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2823,23 +2559,14 @@ private ServiceResponse getSecretDelegate(Response r * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecrets(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getSecretsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getSecretsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -2847,9 +2574,44 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorExcept * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getSecretsAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getSecretsSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the List<SecretItem> object + */ + public Observable>> getSecretsAsync(final String vaultBaseUrl) { + return getSecretsSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getSecretsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getSecretsSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2858,32 +2620,18 @@ public ServiceCall> getSecretsAsync(final String vaultBaseUrl, } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecrets(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getSecretsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getSecretsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getSecrets(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getSecretsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -2897,22 +2645,14 @@ public void onResponse(Call call, Response response) * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecrets(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getSecretsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getSecretsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -2921,9 +2661,46 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorExcept * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param maxresults Maximum number of secrets to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getSecretsAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getSecretsSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param maxresults Maximum number of secrets to return. + * @return the observable to the List<SecretItem> object + */ + public Observable>> getSecretsAsync(final String vaultBaseUrl, final Integer maxresults) { + return getSecretsSinglePageAsync(vaultBaseUrl, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getSecretsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List secrets in the specified vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param maxresults Maximum number of secrets to return. + * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getSecretsSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2931,32 +2708,18 @@ public ServiceCall> getSecretsAsync(final String vaultBaseUrl, throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecrets(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getSecretsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getSecretsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getSecrets(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getSecretsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getSecretsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2977,26 +2740,14 @@ private ServiceResponse> getSecretsDelegate(Response> getSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecretVersions(secretName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getSecretVersionsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getSecretVersionsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -3005,9 +2756,46 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorExcept * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @return the observable to the List<SecretItem> object + */ + public Observable>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName) { + return getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getSecretVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getSecretVersionsSinglePageAsync(final String vaultBaseUrl, final String secretName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3019,32 +2807,18 @@ public ServiceCall> getSecretVersionsAsync(final String vaultBa } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecretVersions(secretName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getSecretVersionsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getSecretVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getSecretVersions(secretName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getSecretVersionsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -3059,25 +2833,35 @@ public void onResponse(Call call, Response response) * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (secretName == null) { - throw new IllegalArgumentException("Parameter secretName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecretVersions(secretName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getSecretVersionsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getSecretVersionsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param maxresults Maximum number of results to return. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); } /** @@ -3086,10 +2870,28 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorExcept * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault * @param maxresults Maximum number of results to return. - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the observable to the List<SecretItem> object + */ + public Observable>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults) { + return getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getSecretVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of the specified secret. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param secretName The name of the secret in the given vault + ServiceResponse> * @param maxresults Maximum number of results to return. + * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceCall> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback serviceCallback) { + public Observable>> getSecretVersionsSinglePageAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3100,32 +2902,18 @@ public ServiceCall> getSecretVersionsAsync(final String vaultBa throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getSecretVersions(secretName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getSecretVersionsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getSecretVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getSecretVersions(secretName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getSecretVersionsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getSecretVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3145,23 +2933,14 @@ private ServiceResponse> getSecretVersionsDelegate(Response * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificates(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getCertificatesDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getCertificatesNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -3169,9 +2948,44 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorE * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificatesAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificatesSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the List<CertificateItem> object + */ + public Observable>> getCertificatesAsync(final String vaultBaseUrl) { + return getCertificatesSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificatesSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3180,32 +2994,18 @@ public ServiceCall> getCertificatesAsync(final String vaul } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificates(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificatesDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificatesNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getCertificates(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificatesDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -3219,22 +3019,14 @@ public void onResponse(Call call, Response response) * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificates(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getCertificatesDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getCertificatesNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -3243,9 +3035,46 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorE * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param maxresults Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificatesAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificatesSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param maxresults Maximum number of results to return. + * @return the observable to the List<CertificateItem> object + */ + public Observable>> getCertificatesAsync(final String vaultBaseUrl, final Integer maxresults) { + return getCertificatesSinglePageAsync(vaultBaseUrl, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List certificates in the specified vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param maxresults Maximum number of results to return. + * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificatesSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3253,32 +3082,18 @@ public ServiceCall> getCertificatesAsync(final String vaul throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificates(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificatesDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificatesNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getCertificates(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificatesDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificatesDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3299,18 +3114,7 @@ private ServiceResponse> getCertificatesDelegate(Respo * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse deleteCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return deleteCertificateDelegate(call.execute()); + return deleteCertificateAsync(vaultBaseUrl, certificateName).toBlocking().single(); } /** @@ -3319,9 +3123,20 @@ public ServiceResponse deleteCertificate(String vaultBaseUrl, * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate in the given vault * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteCertificateAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Deletes a certificate from the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @return the observable to the CertificateBundle object + */ + public Observable> deleteCertificateAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3332,26 +3147,18 @@ public ServiceCall deleteCertificateAsync(String vaultBaseUrl throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = deleteCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.deleteCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3372,19 +3179,7 @@ private ServiceResponse deleteCertificateDelegate(Response setCertificateContacts(String vaultBaseUrl, Contacts contacts) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (contacts == null) { - throw new IllegalArgumentException("Parameter contacts is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - Validator.validate(contacts); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateContacts(contacts, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return setCertificateContactsDelegate(call.execute()); + return setCertificateContactsAsync(vaultBaseUrl, contacts).toBlocking().single(); } /** @@ -3393,9 +3188,20 @@ public ServiceResponse setCertificateContacts(String vaultBaseUrl, Con * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param contacts The contacts for the vault certificates. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts, final ServiceCallback serviceCallback) { + return ServiceCall.create(setCertificateContactsAsync(vaultBaseUrl, contacts), serviceCallback); + } + + /** + * Sets the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param contacts The contacts for the vault certificates. + * @return the observable to the Contacts object + */ + public Observable> setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3407,26 +3213,18 @@ public ServiceCall setCertificateContactsAsync(String vaultBaseUrl, Co } Validator.validate(contacts); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateContacts(contacts, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = setCertificateContactsDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.setCertificateContacts(contacts, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = setCertificateContactsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse setCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3446,15 +3244,7 @@ private ServiceResponse setCertificateContactsDelegate(Response getCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateContacts(this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getCertificateContactsDelegate(call.execute()); + return getCertificateContactsAsync(vaultBaseUrl).toBlocking().single(); } /** @@ -3462,9 +3252,19 @@ public ServiceResponse getCertificateContacts(String vaultBaseUrl) thr * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { + return ServiceCall.create(getCertificateContactsAsync(vaultBaseUrl), serviceCallback); + } + + /** + * Gets the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the Contacts object + */ + public Observable> getCertificateContactsAsync(String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3472,26 +3272,18 @@ public ServiceCall getCertificateContactsAsync(String vaultBaseUrl, fi throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateContacts(this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getCertificateContactsDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.getCertificateContacts(this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getCertificateContactsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3511,15 +3303,7 @@ private ServiceResponse getCertificateContactsDelegate(Response deleteCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificateContacts(this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return deleteCertificateContactsDelegate(call.execute()); + return deleteCertificateContactsAsync(vaultBaseUrl).toBlocking().single(); } /** @@ -3527,9 +3311,19 @@ public ServiceResponse deleteCertificateContacts(String vaultBaseUrl) * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteCertificateContactsAsync(vaultBaseUrl), serviceCallback); + } + + /** + * Deletes the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the Contacts object + */ + public Observable> deleteCertificateContactsAsync(String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3537,26 +3331,18 @@ public ServiceCall deleteCertificateContactsAsync(String vaultBaseUrl, throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificateContacts(this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = deleteCertificateContactsDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.deleteCertificateContacts(this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteCertificateContactsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3576,23 +3362,14 @@ private ServiceResponse deleteCertificateContactsDelegate(Response> getCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateIssuers(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getCertificateIssuersDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getCertificateIssuersNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -3600,9 +3377,44 @@ public Page nextPage(String nextPageLink) throws KeyVault * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificateIssuersAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificateIssuersSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the List<CertificateIssuerItem> object + */ + public Observable>> getCertificateIssuersAsync(final String vaultBaseUrl) { + return getCertificateIssuersSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificateIssuersSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3611,32 +3423,18 @@ public ServiceCall> getCertificateIssuersAsync(final } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateIssuers(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificateIssuersDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificateIssuersNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getCertificateIssuers(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificateIssuersDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -3650,22 +3448,14 @@ public void onResponse(Call call, Response response) * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateIssuers(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getCertificateIssuersDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getCertificateIssuersNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -3674,9 +3464,46 @@ public Page nextPage(String nextPageLink) throws KeyVault * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param maxresults Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param maxresults Maximum number of results to return. + * @return the observable to the List<CertificateIssuerItem> object + */ + public Observable>> getCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults) { + return getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param maxresults Maximum number of results to return. + * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificateIssuersSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3684,32 +3511,18 @@ public ServiceCall> getCertificateIssuersAsync(final throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateIssuers(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificateIssuersDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificateIssuersNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } + return service.getCertificateIssuers(maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificateIssuersDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificateIssuersDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3724,36 +3537,14 @@ private ServiceResponse> getCertificateIssuersDe * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. + * @param provider The issuer provider. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (issuerName == null) { - throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (provider == null) { - throw new IllegalArgumentException("Parameter provider is required and cannot be null."); - } - final IssuerCredentials credentials = null; - final OrganizationDetails organizationDetails = null; - final IssuerAttributes attributes = null; - CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); - parameter.withProvider(provider); - parameter.withCredentials(null); - parameter.withOrganizationDetails(null); - parameter.withAttributes(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - return setCertificateIssuerDelegate(call.execute()); + return setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider).toBlocking().single(); } /** @@ -3761,11 +3552,23 @@ public ServiceResponse setCertificateIssuer(String vaultBaseUrl, S * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. + * @param provider The issuer provider. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback serviceCallback) { + return ServiceCall.create(setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider), serviceCallback); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @return the observable to the IssuerBundle object + */ + public Observable> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3787,26 +3590,18 @@ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, parameter.withOrganizationDetails(null); parameter.withAttributes(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = setCertificateIssuerDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = setCertificateIssuerDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -3814,7 +3609,7 @@ public void onResponse(Call call, Response response) * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. + * @param provider The issuer provider. * @param credentials The credentials to be used for the issuer. * @param organizationDetails Details of the organization as provided to the issuer. * @param attributes Attributes of the issuer object. @@ -3823,30 +3618,8 @@ public void onResponse(Call call, Response response) * @throws IllegalArgumentException exception thrown from invalid parameters * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (issuerName == null) { - throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (provider == null) { - throw new IllegalArgumentException("Parameter provider is required and cannot be null."); - } - Validator.validate(credentials); - Validator.validate(organizationDetails); - Validator.validate(attributes); - CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); - parameter.withProvider(provider); - parameter.withCredentials(credentials); - parameter.withOrganizationDetails(organizationDetails); - parameter.withAttributes(attributes); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - return setCertificateIssuerDelegate(call.execute()); + public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single(); } /** @@ -3854,14 +3627,29 @@ public ServiceResponse setCertificateIssuer(String vaultBaseUrl, S * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. + * @param provider The issuer provider. * @param credentials The credentials to be used for the issuer. * @param organizationDetails Details of the organization as provided to the issuer. * @param attributes Attributes of the issuer object. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { + return ServiceCall.create(setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @return the observable to the IssuerBundle object + */ + public Observable> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3883,26 +3671,18 @@ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, parameter.withOrganizationDetails(organizationDetails); parameter.withAttributes(attributes); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = setCertificateIssuerDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = setCertificateIssuerDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse setCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3917,36 +3697,13 @@ private ServiceResponse setCertificateIssuerDelegate(Response updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (issuerName == null) { - throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (provider == null) { - throw new IllegalArgumentException("Parameter provider is required and cannot be null."); - } - final IssuerCredentials credentials = null; - final OrganizationDetails organizationDetails = null; - final IssuerAttributes attributes = null; - CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); - parameter.withProvider(provider); - parameter.withCredentials(null); - parameter.withOrganizationDetails(null); - parameter.withAttributes(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - return updateCertificateIssuerDelegate(call.execute()); + public ServiceResponse updateCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateIssuerAsync(vaultBaseUrl, issuerName).toBlocking().single(); } /** @@ -3954,11 +3711,21 @@ public ServiceResponse updateCertificateIssuer(String vaultBaseUrl * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateIssuerAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object */ - public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback serviceCallback) { + public Observable> updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3968,38 +3735,28 @@ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUr if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - if (provider == null) { - throw new IllegalArgumentException("Parameter provider is required and cannot be null."); - } + final String provider = null; final IssuerCredentials credentials = null; final OrganizationDetails organizationDetails = null; final IssuerAttributes attributes = null; CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); - parameter.withProvider(provider); + parameter.withProvider(null); parameter.withCredentials(null); parameter.withOrganizationDetails(null); parameter.withAttributes(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateCertificateIssuerDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateCertificateIssuerDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -4007,7 +3764,7 @@ public void onResponse(Call call, Response response) * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. + * @param provider The issuer provider. * @param credentials The credentials to be used for the issuer. * @param organizationDetails Details of the organization as provided to the issuer. * @param attributes Attributes of the issuer object. @@ -4017,29 +3774,7 @@ public void onResponse(Call call, Response response) * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (issuerName == null) { - throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (provider == null) { - throw new IllegalArgumentException("Parameter provider is required and cannot be null."); - } - Validator.validate(credentials); - Validator.validate(organizationDetails); - Validator.validate(attributes); - CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); - parameter.withProvider(provider); - parameter.withCredentials(credentials); - parameter.withOrganizationDetails(organizationDetails); - parameter.withAttributes(attributes); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - return updateCertificateIssuerDelegate(call.execute()); + return updateCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single(); } /** @@ -4047,14 +3782,29 @@ public ServiceResponse updateCertificateIssuer(String vaultBaseUrl * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. - * @param provider The name of the issuer. + * @param provider The issuer provider. * @param credentials The credentials to be used for the issuer. * @param organizationDetails Details of the organization as provided to the issuer. * @param attributes Attributes of the issuer object. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @return the observable to the IssuerBundle object + */ + public Observable> updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4064,9 +3814,6 @@ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUr if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } - if (provider == null) { - throw new IllegalArgumentException("Parameter provider is required and cannot be null."); - } Validator.validate(credentials); Validator.validate(organizationDetails); Validator.validate(attributes); @@ -4076,26 +3823,18 @@ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUr parameter.withOrganizationDetails(organizationDetails); parameter.withAttributes(attributes); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateCertificateIssuerDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.updateCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateCertificateIssuerDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4116,18 +3855,7 @@ private ServiceResponse updateCertificateIssuerDelegate(Response getCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (issuerName == null) { - throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getCertificateIssuerDelegate(call.execute()); + return getCertificateIssuerAsync(vaultBaseUrl, issuerName).toBlocking().single(); } /** @@ -4136,9 +3864,20 @@ public ServiceResponse getCertificateIssuer(String vaultBaseUrl, S * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return ServiceCall.create(getCertificateIssuerAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Gets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object + */ + public Observable> getCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4149,26 +3888,18 @@ public ServiceCall getCertificateIssuerAsync(String vaultBaseUrl, throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getCertificateIssuerDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.getCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getCertificateIssuerDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4189,18 +3920,7 @@ private ServiceResponse getCertificateIssuerDelegate(Response deleteCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (issuerName == null) { - throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return deleteCertificateIssuerDelegate(call.execute()); + return deleteCertificateIssuerAsync(vaultBaseUrl, issuerName).toBlocking().single(); } /** @@ -4209,9 +3929,20 @@ public ServiceResponse deleteCertificateIssuer(String vaultBaseUrl * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param issuerName The name of the issuer. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteCertificateIssuerAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Deletes the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object + */ + public Observable> deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4222,26 +3953,18 @@ public ServiceCall deleteCertificateIssuerAsync(String vaultBaseUr throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = deleteCertificateIssuerDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.deleteCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteCertificateIssuerDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4262,25 +3985,7 @@ private ServiceResponse deleteCertificateIssuerDelegate(Response createCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final CertificatePolicy certificatePolicy = null; - final CertificateAttributes certificateAttributes = null; - final Map tags = null; - CertificateCreateParameters parameters = new CertificateCreateParameters(); - parameters.withCertificatePolicy(null); - parameters.withCertificateAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return createCertificateDelegate(call.execute()); + return createCertificateAsync(vaultBaseUrl, certificateName).toBlocking().single(); } /** @@ -4289,9 +3994,20 @@ public ServiceResponse createCertificate(String vaultBaseU * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall createCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(createCertificateAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Creates a new certificate version. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the CertificateOperation object + */ + public Observable> createCertificateAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4309,26 +4025,18 @@ public ServiceCall createCertificateAsync(String vaultBase parameters.withCertificateAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = createCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.createCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -4345,25 +4053,7 @@ public void onResponse(Call call, Response response) * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse createCertificate(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - Validator.validate(certificatePolicy); - Validator.validate(certificateAttributes); - Validator.validate(tags); - CertificateCreateParameters parameters = new CertificateCreateParameters(); - parameters.withCertificatePolicy(certificatePolicy); - parameters.withCertificateAttributes(certificateAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return createCertificateDelegate(call.execute()); + return createCertificateAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags).toBlocking().single(); } /** @@ -4375,9 +4065,23 @@ public ServiceResponse createCertificate(String vaultBaseU * @param certificateAttributes The attributes of the certificate (optional) * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall createCertificateAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(createCertificateAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Creates a new certificate version. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param certificatePolicy The management policy for the certificate + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateOperation object + */ + public Observable> createCertificateAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4395,26 +4099,18 @@ public ServiceCall createCertificateAsync(String vaultBase parameters.withCertificateAttributes(certificateAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.createCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = createCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.createCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse createCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4436,31 +4132,7 @@ private ServiceResponse createCertificateDelegate(Response * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (base64EncodedCertificate == null) { - throw new IllegalArgumentException("Parameter base64EncodedCertificate is required and cannot be null."); - } - final String password = null; - final CertificatePolicy certificatePolicy = null; - final CertificateAttributes certificateAttributes = null; - final Map tags = null; - CertificateImportParameters parameters = new CertificateImportParameters(); - parameters.withBase64EncodedCertificate(base64EncodedCertificate); - parameters.withPassword(null); - parameters.withCertificatePolicy(null); - parameters.withCertificateAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return importCertificateDelegate(call.execute()); + return importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).toBlocking().single(); } /** @@ -4470,9 +4142,21 @@ public ServiceResponse importCertificate(String vaultBaseUrl, * @param certificateName The name of the certificate * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, final ServiceCallback serviceCallback) { + return ServiceCall.create(importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate), serviceCallback); + } + + /** + * Imports a certificate into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @return the observable to the CertificateBundle object + */ + public Observable> importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4496,26 +4180,18 @@ public ServiceCall importCertificateAsync(String vaultBaseUrl parameters.withCertificateAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = importCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.importCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = importCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -4534,30 +4210,24 @@ public void onResponse(Call call, Response response) * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (base64EncodedCertificate == null) { - throw new IllegalArgumentException("Parameter base64EncodedCertificate is required and cannot be null."); - } - Validator.validate(certificatePolicy); - Validator.validate(certificateAttributes); - Validator.validate(tags); - CertificateImportParameters parameters = new CertificateImportParameters(); - parameters.withBase64EncodedCertificate(base64EncodedCertificate); - parameters.withPassword(password); - parameters.withCertificatePolicy(certificatePolicy); - parameters.withCertificateAttributes(certificateAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return importCertificateDelegate(call.execute()); + return importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).toBlocking().single(); + } + + /** + * Imports a certificate into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption + * @param certificatePolicy The management policy for the certificate + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags), serviceCallback); } /** @@ -4570,10 +4240,9 @@ public ServiceResponse importCertificate(String vaultBaseUrl, * @param certificatePolicy The management policy for the certificate * @param certificateAttributes The attributes of the certificate (optional) * @param tags Application-specific metadata in the form of key-value pairs - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the observable to the CertificateBundle object */ - public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + public Observable> importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4596,26 +4265,18 @@ public ServiceCall importCertificateAsync(String vaultBaseUrl parameters.withCertificateAttributes(certificateAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.importCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = importCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.importCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = importCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse importCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4636,26 +4297,14 @@ private ServiceResponse importCertificateDelegate(Response> getCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final Integer maxresults = null; - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateVersions(certificateName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getCertificateVersionsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getCertificateVersionsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -4664,9 +4313,46 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorE * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the List<CertificateItem> object + */ + public Observable>> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName) { + return getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificateVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificateVersionsSinglePageAsync(final String vaultBaseUrl, final String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4678,32 +4364,18 @@ public ServiceCall> getCertificateVersionsAsync(final Stri } final Integer maxresults = null; String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateVersions(certificateName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificateVersionsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificateVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getCertificateVersions(certificateName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificateVersionsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -4718,25 +4390,14 @@ public void onResponse(Call call, Response response) * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> getCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateVersions(certificateName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - ServiceResponse> response = getCertificateVersionsDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws KeyVaultErrorException, IOException { - return getCertificateVersionsNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -4746,9 +4407,48 @@ public Page nextPage(String nextPageLink) throws KeyVaultErrorE * @param certificateName The name of the certificate * @param maxresults Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param maxresults Maximum number of results to return. + * @return the observable to the List<CertificateItem> object + */ + public Observable>> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { + return getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificateVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of a certificate. + * + ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + ServiceResponse> * @param certificateName The name of the certificate + ServiceResponse> * @param maxresults Maximum number of results to return. + * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificateVersionsSinglePageAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4759,32 +4459,18 @@ public ServiceCall> getCertificateVersionsAsync(final Stri throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateVersions(certificateName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall> serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificateVersionsDelegate(response); - if (serviceCallback != null) { - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificateVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getCertificateVersions(certificateName, maxresults, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificateVersionsDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificateVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4805,18 +4491,7 @@ private ServiceResponse> getCertificateVersionsDelegat * @return the CertificatePolicy object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getCertificatePolicy(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificatePolicy(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getCertificatePolicyDelegate(call.execute()); + return getCertificatePolicyAsync(vaultBaseUrl, certificateName).toBlocking().single(); } /** @@ -4825,9 +4500,20 @@ public ServiceResponse getCertificatePolicy(String vaultBaseU * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate in the given vault. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getCertificatePolicyAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(getCertificatePolicyAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Gets the policy for a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault. + * @return the observable to the CertificatePolicy object + */ + public Observable> getCertificatePolicyAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4838,26 +4524,18 @@ public ServiceCall getCertificatePolicyAsync(String vaultBase throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificatePolicy(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getCertificatePolicyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.getCertificatePolicy(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getCertificatePolicyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificatePolicyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4879,22 +4557,7 @@ private ServiceResponse getCertificatePolicyDelegate(Response * @return the CertificatePolicy object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse updateCertificatePolicy(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (certificatePolicy == null) { - throw new IllegalArgumentException("Parameter certificatePolicy is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - Validator.validate(certificatePolicy); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificatePolicy(certificateName, certificatePolicy, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return updateCertificatePolicyDelegate(call.execute()); + return updateCertificatePolicyAsync(vaultBaseUrl, certificateName, certificatePolicy).toBlocking().single(); } /** @@ -4904,9 +4567,21 @@ public ServiceResponse updateCertificatePolicy(String vaultBa * @param certificateName The name of the certificate in the given vault. * @param certificatePolicy The policy for the certificate. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificatePolicyAsync(vaultBaseUrl, certificateName, certificatePolicy), serviceCallback); + } + + /** + * Updates the policy for a certificate. Set appropriate members in the certificatePolicy that must be updated. Leave others as null. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault. + * @param certificatePolicy The policy for the certificate. + * @return the observable to the CertificatePolicy object + */ + public Observable> updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4921,26 +4596,18 @@ public ServiceCall updateCertificatePolicyAsync(String vaultB } Validator.validate(certificatePolicy); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificatePolicy(certificateName, certificatePolicy, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateCertificatePolicyDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.updateCertificatePolicy(certificateName, certificatePolicy, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateCertificatePolicyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateCertificatePolicyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4962,28 +4629,7 @@ private ServiceResponse updateCertificatePolicyDelegate(Respo * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (certificateVersion == null) { - throw new IllegalArgumentException("Parameter certificateVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - final CertificatePolicy certificatePolicy = null; - final CertificateAttributes certificateAttributes = null; - final Map tags = null; - CertificateUpdateParameters parameters = new CertificateUpdateParameters(); - parameters.withCertificatePolicy(null); - parameters.withCertificateAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return updateCertificateDelegate(call.execute()); + return updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single(); } /** @@ -4993,9 +4639,21 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, * @param certificateName The name of the certificate in the given vault * @param certificateVersion The version of the certificate * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + } + + /** + * Updates the attributes associated with the specified certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @param certificateVersion The version of the certificate + * @return the observable to the CertificateBundle object + */ + public Observable> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5016,26 +4674,18 @@ public ServiceCall updateCertificateAsync(String vaultBaseUrl parameters.withCertificateAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.updateCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -5053,28 +4703,7 @@ public void onResponse(Call call, Response response) * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (certificateVersion == null) { - throw new IllegalArgumentException("Parameter certificateVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - Validator.validate(certificatePolicy); - Validator.validate(certificateAttributes); - Validator.validate(tags); - CertificateUpdateParameters parameters = new CertificateUpdateParameters(); - parameters.withCertificatePolicy(certificatePolicy); - parameters.withCertificateAttributes(certificateAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return updateCertificateDelegate(call.execute()); + return updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).toBlocking().single(); } /** @@ -5087,9 +4716,24 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, * @param certificateAttributes The attributes of the certificate (optional) * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Updates the attributes associated with the specified certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @param certificateVersion The version of the certificate + * @param certificatePolicy The management policy for the certificate + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateBundle object + */ + public Observable> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5110,26 +4754,18 @@ public ServiceCall updateCertificateAsync(String vaultBaseUrl parameters.withCertificateAttributes(certificateAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.updateCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5151,21 +4787,7 @@ private ServiceResponse updateCertificateDelegate(Response getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (certificateVersion == null) { - throw new IllegalArgumentException("Parameter certificateVersion is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getCertificateDelegate(call.execute()); + return getCertificateAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single(); } /** @@ -5175,9 +4797,21 @@ public ServiceResponse getCertificate(String vaultBaseUrl, St * @param certificateName The name of the certificate in the given vault * @param certificateVersion The version of the certificate * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(getCertificateAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + } + + /** + * Gets a Certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @param certificateVersion The version of the certificate + * @return the observable to the CertificateBundle object + */ + public Observable> getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5191,26 +4825,18 @@ public ServiceCall getCertificateAsync(String vaultBaseUrl, S throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.getCertificate(certificateName, certificateVersion, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5232,20 +4858,7 @@ private ServiceResponse getCertificateDelegate(Response updateCertificateOperation(String vaultBaseUrl, String certificateName, boolean cancellationRequested) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); - certificateOperation.withCancellationRequested(cancellationRequested); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), certificateOperation, parameterizedHost, this.userAgent()); - return updateCertificateOperationDelegate(call.execute()); + return updateCertificateOperationAsync(vaultBaseUrl, certificateName, cancellationRequested).toBlocking().single(); } /** @@ -5255,9 +4868,21 @@ public ServiceResponse updateCertificateOperation(String v * @param certificateName The name of the certificate * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateOperationAsync(vaultBaseUrl, certificateName, cancellationRequested), serviceCallback); + } + + /** + * Updates a certificate operation. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. + * @return the observable to the CertificateOperation object + */ + public Observable> updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5270,26 +4895,18 @@ public ServiceCall updateCertificateOperationAsync(String CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); certificateOperation.withCancellationRequested(cancellationRequested); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), certificateOperation, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = updateCertificateOperationDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.updateCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), certificateOperation, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateCertificateOperationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateCertificateOperationDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5310,18 +4927,7 @@ private ServiceResponse updateCertificateOperationDelegate * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return getCertificateOperationDelegate(call.execute()); + return getCertificateOperationAsync(vaultBaseUrl, certificateName).toBlocking().single(); } /** @@ -5330,9 +4936,20 @@ public ServiceResponse getCertificateOperation(String vaul * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall getCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(getCertificateOperationAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Gets the certificate operation response. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the CertificateOperation object + */ + public Observable> getCertificateOperationAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5343,26 +4960,18 @@ public ServiceCall getCertificateOperationAsync(String vau throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.getCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = getCertificateOperationDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + return service.getCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getCertificateOperationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificateOperationDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5383,18 +4992,7 @@ private ServiceResponse getCertificateOperationDelegate(Re * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse deleteCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return deleteCertificateOperationDelegate(call.execute()); + return deleteCertificateOperationAsync(vaultBaseUrl, certificateName).toBlocking().single(); } /** @@ -5403,9 +5001,20 @@ public ServiceResponse deleteCertificateOperation(String v * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteCertificateOperationAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Deletes the certificate operation. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the CertificateOperation object + */ + public Observable> deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5416,26 +5025,18 @@ public ServiceCall deleteCertificateOperationAsync(String throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.deleteCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = deleteCertificateOperationDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.deleteCertificateOperation(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteCertificateOperationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteCertificateOperationDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5457,28 +5058,7 @@ private ServiceResponse deleteCertificateOperationDelegate * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (x509Certificates == null) { - throw new IllegalArgumentException("Parameter x509Certificates is required and cannot be null."); - } - Validator.validate(x509Certificates); - final CertificateAttributes certificateAttributes = null; - final Map tags = null; - CertificateMergeParameters parameters = new CertificateMergeParameters(); - parameters.withX509Certificates(x509Certificates); - parameters.withCertificateAttributes(null); - parameters.withTags(null); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.mergeCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return mergeCertificateDelegate(call.execute()); + return mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates).toBlocking().single(); } /** @@ -5488,9 +5068,21 @@ public ServiceResponse mergeCertificate(String vaultBaseUrl, * @param certificateName The name of the certificate * @param x509Certificates The certificate or the certificate chain to merge * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, final ServiceCallback serviceCallback) { + return ServiceCall.create(mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates), serviceCallback); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param x509Certificates The certificate or the certificate chain to merge + * @return the observable to the CertificateBundle object + */ + public Observable> mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5511,26 +5103,18 @@ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, parameters.withCertificateAttributes(null); parameters.withTags(null); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.mergeCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = mergeCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.mergeCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = mergeCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -5547,28 +5131,7 @@ public void onResponse(Call call, Response response) * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (vaultBaseUrl == null) { - throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); - } - if (certificateName == null) { - throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); - } - if (this.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); - } - if (x509Certificates == null) { - throw new IllegalArgumentException("Parameter x509Certificates is required and cannot be null."); - } - Validator.validate(x509Certificates); - Validator.validate(certificateAttributes); - Validator.validate(tags); - CertificateMergeParameters parameters = new CertificateMergeParameters(); - parameters.withX509Certificates(x509Certificates); - parameters.withCertificateAttributes(certificateAttributes); - parameters.withTags(tags); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.mergeCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - return mergeCertificateDelegate(call.execute()); + return mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags).toBlocking().single(); } /** @@ -5580,9 +5143,23 @@ public ServiceResponse mergeCertificate(String vaultBaseUrl, * @param certificateAttributes The attributes of the certificate (optional) * @param tags Application-specific metadata in the form of key-value pairs * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags), serviceCallback); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param x509Certificates The certificate or the certificate chain to merge + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateBundle object + */ + public Observable> mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5603,26 +5180,18 @@ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, parameters.withCertificateAttributes(certificateAttributes); parameters.withTags(tags); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.mergeCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()); - final ServiceCall serviceCall = new ServiceCall<>(call); - call.enqueue(new ServiceResponseCallback(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse clientResponse = mergeCertificateDelegate(response); - if (serviceCallback != null) { - serviceCallback.success(clientResponse); + return service.mergeCertificate(certificateName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = mergeCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse mergeCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5641,12 +5210,15 @@ private ServiceResponse mergeCertificateDelegate(Response> getKeyVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getKeyVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getKeyVersionsNextDelegate(call.execute()); + public ServiceResponse> getKeyVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5655,35 +5227,59 @@ public ServiceResponse> getKeyVersionsNext(final String nextPa * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getKeyVersionsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getKeyVersionsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of the specified key. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<KeyItem> object + */ + public Observable>> getKeyVersionsNextAsync(final String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of the specified key. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getKeyVersionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getKeyVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getKeyVersionsNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getKeyVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getKeyVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getKeyVersionsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getKeyVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5702,12 +5298,15 @@ private ServiceResponse> getKeyVersionsNextDelegate(Response> getKeysNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getKeysNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getKeysNextDelegate(call.execute()); + public ServiceResponse> getKeysNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeysNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5716,35 +5315,59 @@ public ServiceResponse> getKeysNext(final String nextPageLink) * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getKeysNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getKeysNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List keys in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<KeyItem> object + */ + public Observable>> getKeysNextAsync(final String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getKeysNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List keys in the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getKeysNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getKeysNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getKeysNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getKeysNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getKeysNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getKeysNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getKeysNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5763,12 +5386,15 @@ private ServiceResponse> getKeysNextDelegate(Response> getSecretsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getSecretsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getSecretsNextDelegate(call.execute()); + public ServiceResponse> getSecretsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5777,35 +5403,59 @@ public ServiceResponse> getSecretsNext(final String nextPag * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getSecretsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getSecretsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List secrets in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<SecretItem> object + */ + public Observable>> getSecretsNextAsync(final String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getSecretsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List secrets in the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getSecretsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getSecretsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getSecretsNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getSecretsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getSecretsNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getSecretsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getSecretsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5824,12 +5474,15 @@ private ServiceResponse> getSecretsNextDelegate(Response> getSecretVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getSecretVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getSecretVersionsNextDelegate(call.execute()); + public ServiceResponse> getSecretVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5838,35 +5491,59 @@ public ServiceResponse> getSecretVersionsNext(final String * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getSecretVersionsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getSecretVersionsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of the specified secret. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<SecretItem> object + */ + public Observable>> getSecretVersionsNextAsync(final String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getSecretVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of the specified secret. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getSecretVersionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getSecretVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getSecretVersionsNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getSecretVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getSecretVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getSecretVersionsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getSecretVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5885,12 +5562,15 @@ private ServiceResponse> getSecretVersionsNextDelegate(Resp * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificatesNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getCertificatesNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getCertificatesNextDelegate(call.execute()); + public ServiceResponse> getCertificatesNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5899,35 +5579,59 @@ public ServiceResponse> getCertificatesNext(final Stri * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificatesNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificatesNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificates in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<CertificateItem> object + */ + public Observable>> getCertificatesNextAsync(final String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List certificates in the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificatesNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getCertificatesNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificatesNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificatesNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getCertificatesNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificatesNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificatesNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5946,12 +5650,15 @@ private ServiceResponse> getCertificatesNextDelegate(R * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificateIssuersNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getCertificateIssuersNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getCertificateIssuersNextDelegate(call.execute()); + public ServiceResponse> getCertificateIssuersNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5960,35 +5667,59 @@ public ServiceResponse> getCertificateIssuersNex * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificateIssuersNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificateIssuersNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificate issuers for the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<CertificateIssuerItem> object + */ + public Observable>> getCertificateIssuersNextAsync(final String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificateIssuersNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getCertificateIssuersNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificateIssuersNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificateIssuersNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getCertificateIssuersNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificateIssuersNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificateIssuersNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -6007,12 +5738,15 @@ private ServiceResponse> getCertificateIssuersNe * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getCertificateVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.getCertificateVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - return getCertificateVersionsNextDelegate(call.execute()); + public ServiceResponse> getCertificateVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + PagedList pagedList = new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; + return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -6021,35 +5755,59 @@ public ServiceResponse> getCertificateVersionsNext(fin * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ public ServiceCall> getCertificateVersionsNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getCertificateVersionsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List the versions of a certificate. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the List<CertificateItem> object + */ + public Observable>> getCertificateVersionsNextAsync(final String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + return getCertificateVersionsNextSinglePageAsync(nextPageLink); + } + }); + } + + /** + * List the versions of a certificate. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getCertificateVersionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getCertificateVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCall, serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getCertificateVersionsNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getCertificateVersionsNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getCertificateVersionsNext(nextPageLink, this.acceptLanguage(), this.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getCertificateVersionsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificateVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java index f90e86cd39fdb..2edac49304f93 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java @@ -21,7 +21,7 @@ public class CertificateIssuerItem { private String id; /** - * The name of the issuer. + * The issuer provider. */ private String provider; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java index f9daf44e44fda..df352850dff30 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java @@ -17,7 +17,7 @@ */ public class CertificateIssuerSetParameters { /** - * The name of the issuer. + * The issuer provider. */ @JsonProperty(required = true) private String provider; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java index 7af311457b0ea..05d62b4ec54d9 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java @@ -13,13 +13,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * The certificate issuer set parameters. + * The certificate issuer update parameters. */ public class CertificateIssuerUpdateParameters { /** - * The name of the issuer. + * The issuer provider. */ - @JsonProperty(required = true) private String provider; /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java index dd7c42a5f4ac0..b2cd7b05f1189 100644 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java @@ -13,7 +13,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * A certificate operation is returned in case of async requests. + * The certificate operation update parameters. */ public class CertificateOperationUpdateParameter { /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java index e30c98684da69..59b4d7f2afca1 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java @@ -30,7 +30,7 @@ public class IssuerBundle { private String id; /** - * The name of the issuer. + * The issuer provider. */ private String provider; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerReference.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerReference.java index 6f971897b7dbb..c2aa1dbe1f77e 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerReference.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerReference.java @@ -16,7 +16,8 @@ */ public class IssuerReference { /** - * Name of the referenced issuer object. + * Name of the referenced issuer object or reserved names e.g. 'Self', + * 'Unknown'. */ private String name; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java index e7ce6cc2b0fb1..07fff30be2e88 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java @@ -19,6 +19,7 @@ import com.microsoft.azure.keyvault.KeyIdentifier; import com.microsoft.azure.keyvault.webkey.JsonWebKey; import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; +import com.fasterxml.jackson.annotation.JsonProperty; /** * A KeyBundle consisting of a WebKey plus its Attributes. @@ -40,8 +41,10 @@ public class KeyBundle { private Map tags; /** - * True if the secret's lifetime is managed by key vault. + * True if the key's lifetime is managed by key vault i.e. if this is a + * key backing a certificate, then managed will be true. */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java index a799ee36fb6e7..9d61d685cee94 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java @@ -13,6 +13,8 @@ import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; /** * The key create parameters. @@ -20,10 +22,11 @@ public class KeyCreateParameters { /** * The type of key to create. Valid key types, see JsonWebKeyType. - * Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct'. + * Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, + * Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct'. */ @JsonProperty(required = true) - private String kty; + private JsonWebKeyType kty; /** * The key size in bytes. e.g. 1024 or 2048. @@ -35,7 +38,7 @@ public class KeyCreateParameters { * The keyOps property. */ @JsonProperty(value = "key_ops") - private List keyOps; + private List keyOps; /** * The keyAttributes property. @@ -53,7 +56,7 @@ public class KeyCreateParameters { * * @return the kty value */ - public String kty() { + public JsonWebKeyType kty() { return this.kty; } @@ -63,7 +66,7 @@ public String kty() { * @param kty the kty value to set * @return the KeyCreateParameters object itself. */ - public KeyCreateParameters withKty(String kty) { + public KeyCreateParameters withKty(JsonWebKeyType kty) { this.kty = kty; return this; } @@ -93,7 +96,7 @@ public KeyCreateParameters withKeySize(Integer keySize) { * * @return the keyOps value */ - public List keyOps() { + public List keyOps() { return this.keyOps; } @@ -103,7 +106,7 @@ public List keyOps() { * @param keyOps the keyOps value to set * @return the KeyCreateParameters object itself. */ - public KeyCreateParameters withKeyOps(List keyOps) { + public KeyCreateParameters withKeyOps(List keyOps) { this.keyOps = keyOps; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java index 4dea299b81d8c..57f669af5a4b7 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java @@ -13,6 +13,7 @@ import java.util.Map; import com.microsoft.azure.keyvault.KeyIdentifier; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The key item containing key metadata. @@ -34,8 +35,10 @@ public class KeyItem { private Map tags; /** - * True if the secret's lifetime is managed by key vault. + * True if the key's lifetime is managed by key vault i.e. if this is a + * key backing a certificate, then managed will be true. */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java index 228a944624152..d65ddea14591e 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java @@ -10,6 +10,7 @@ package com.microsoft.azure.keyvault.models; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; import com.microsoft.rest.Base64Url; import com.fasterxml.jackson.annotation.JsonProperty; @@ -21,7 +22,7 @@ public class KeyOperationsParameters { * algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'. */ @JsonProperty(value = "alg", required = true) - private String algorithm; + private JsonWebKeyEncryptionAlgorithm algorithm; /** * The value property. @@ -34,7 +35,7 @@ public class KeyOperationsParameters { * * @return the algorithm value */ - public String algorithm() { + public JsonWebKeyEncryptionAlgorithm algorithm() { return this.algorithm; } @@ -44,7 +45,7 @@ public String algorithm() { * @param algorithm the algorithm value to set * @return the KeyOperationsParameters object itself. */ - public KeyOperationsParameters withAlgorithm(String algorithm) { + public KeyOperationsParameters withAlgorithm(JsonWebKeyEncryptionAlgorithm algorithm) { this.algorithm = algorithm; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java index 999ed545fd0be..a82bbe119d6b7 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java @@ -28,7 +28,7 @@ public class KeyProperties { private String keyType; /** - * The key size in bytes. e.g. 1024 or 2048. + * The key size in bytes. e.g. 2048. */ @JsonProperty(value = "key_size") private Integer keySize; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java index 1af4965c7b756..838b54f7a964a 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java @@ -10,6 +10,7 @@ package com.microsoft.azure.keyvault.models; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; import com.microsoft.rest.Base64Url; import com.fasterxml.jackson.annotation.JsonProperty; @@ -23,7 +24,7 @@ public class KeySignParameters { * values include: 'RS256', 'RS384', 'RS512', 'RSNULL'. */ @JsonProperty(value = "alg", required = true) - private String algorithm; + private JsonWebKeySignatureAlgorithm algorithm; /** * The value property. @@ -36,7 +37,7 @@ public class KeySignParameters { * * @return the algorithm value */ - public String algorithm() { + public JsonWebKeySignatureAlgorithm algorithm() { return this.algorithm; } @@ -46,7 +47,7 @@ public String algorithm() { * @param algorithm the algorithm value to set * @return the KeySignParameters object itself. */ - public KeySignParameters withAlgorithm(String algorithm) { + public KeySignParameters withAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { this.algorithm = algorithm; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java index 33c51dc4d697b..043fbe2d44fd3 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; /** * The key update parameters. @@ -23,7 +24,7 @@ public class KeyUpdateParameters { * operations, see JsonWebKeyOperation. */ @JsonProperty(value = "key_ops") - private List keyOps; + private List keyOps; /** * The keyAttributes property. @@ -41,7 +42,7 @@ public class KeyUpdateParameters { * * @return the keyOps value */ - public List keyOps() { + public List keyOps() { return this.keyOps; } @@ -51,7 +52,7 @@ public List keyOps() { * @param keyOps the keyOps value to set * @return the KeyUpdateParameters object itself. */ - public KeyUpdateParameters withKeyOps(List keyOps) { + public KeyUpdateParameters withKeyOps(List keyOps) { this.keyOps = keyOps; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java index 1f370f7494ed7..96fd4cb07f947 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java @@ -10,6 +10,7 @@ package com.microsoft.azure.keyvault.models; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; import com.microsoft.rest.Base64Url; import com.fasterxml.jackson.annotation.JsonProperty; @@ -23,7 +24,7 @@ public class KeyVerifyParameters { * include: 'RS256', 'RS384', 'RS512', 'RSNULL'. */ @JsonProperty(value = "alg", required = true) - private String algorithm; + private JsonWebKeySignatureAlgorithm algorithm; /** * The digest used for signing. @@ -42,7 +43,7 @@ public class KeyVerifyParameters { * * @return the algorithm value */ - public String algorithm() { + public JsonWebKeySignatureAlgorithm algorithm() { return this.algorithm; } @@ -52,7 +53,7 @@ public String algorithm() { * @param algorithm the algorithm value to set * @return the KeyVerifyParameters object itself. */ - public KeyVerifyParameters withAlgorithm(String algorithm) { + public KeyVerifyParameters withAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { this.algorithm = algorithm; return this; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java index 6dea046e03cc5..2035765e09b95 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -49,13 +50,17 @@ public class SecretBundle { private Map tags; /** - * The key id for certificate. + * If this is a secret backing a KV certificate, then this field specifies + * the corresponding key backing the KV certificate. */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private String kid; /** - * True if the secret's lifetime is managed by key vault. + * True if the secret's lifetime is managed by key vault i.e. if this is a + * secret backing a certificate, then managed will be true. */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java index db383c7f7f0fb..9c4c31e91d44a 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java @@ -13,6 +13,7 @@ import java.util.Map; import com.microsoft.azure.keyvault.SecretIdentifier; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The secret item containing secret metadata. @@ -39,8 +40,10 @@ public class SecretItem { private String contentType; /** - * True if the secret's lifetime is managed by key vault. + * True if the secret's lifetime is managed by key vault i.e. if this is a + * key backing a certificate, then managed will be true. */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java index ae9267dba24d6..34b1889e212ee 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java @@ -23,7 +23,7 @@ public class X509CertificateProperties { private String subject; /** - * The enhaunced key usage. + * The enhanced key usage. */ private List ekus; @@ -40,7 +40,7 @@ public class X509CertificateProperties { private List keyUsage; /** - * The subject alternate names. + * The duration that the ceritifcate is valid in months. */ @JsonProperty(value = "validity_months") private Integer validityInMonths; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java index e197baa16c33b..8aee1468265fb 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java @@ -7,6 +7,8 @@ import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.KeyAttributes; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; /** * The create key request class. @@ -15,9 +17,9 @@ public final class CreateKeyRequest { private final String vaultBaseUrl; private final String keyName; - private final String keyType; + private final JsonWebKeyType keyType; private final Integer keySize; - private final List keyOperations; + private final List keyOperations; private final KeyAttributes keyAttributes; private final Map tags; @@ -29,11 +31,11 @@ public static class Builder { // Required parameters private final String vaultBaseUrl; private final String keyName; - private final String keyType; + private final JsonWebKeyType keyType; // Optional parameters private Integer keySize; - private List keyOperations; + private List keyOperations; private KeyAttributes attributes; private Map tags; @@ -45,10 +47,11 @@ public static class Builder { * @param keyName * The name of the key in the given vault * @param keyType - * The type of key to create. Possible values include: 'EC', - * 'RSA', 'RSA-HSM', 'oct' + * The type of key to create. Valid key types, see JsonWebKeyType. + * Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. + * Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' */ - public Builder(String vaultBaseUrl, String keyName, String keyType) { + public Builder(String vaultBaseUrl, String keyName, JsonWebKeyType keyType) { this.vaultBaseUrl = vaultBaseUrl; this.keyName = keyName; this.keyType = keyType; @@ -73,7 +76,7 @@ public Builder withKeySize(Integer size) { * the key operation list. * @return the Builder object itself. */ - public Builder withKeyOperations(List keyOperations) { + public Builder withKeyOperations(List keyOperations) { this.keyOperations = keyOperations; return this; } @@ -120,7 +123,7 @@ private CreateKeyRequest(Builder builder) { keySize = builder.keySize; if (builder.keyOperations != null) { - keyOperations = new ArrayList(builder.keyOperations); + keyOperations = new ArrayList(builder.keyOperations); } else { keyOperations = null; } @@ -156,7 +159,7 @@ public String keyName() { /** * @return the key type */ - public String keyType() { + public JsonWebKeyType keyType() { return keyType; } @@ -170,7 +173,7 @@ public Integer keySize() { /** * @return the key operations */ - public List keyOperations() { + public List keyOperations() { return keyOperations; } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java index 91adae60c3ce8..908881d78bb92 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java @@ -7,6 +7,7 @@ import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.KeyAttributes; import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; /** * The import key request class. @@ -110,7 +111,7 @@ private ImportKeyRequest(Builder builder) { .withD(builder.key.d()).withP(builder.key.p()).withQ(builder.key.q()).withDp(builder.key.dp()) .withDq(builder.key.dq()).withQi(builder.key.qi()).withK(builder.key.k()).withT(builder.key.t()); if (builder.key.keyOps() != null) { - key.withKeyOps(new ArrayList(builder.key.keyOps())); + key.withKeyOps(new ArrayList(builder.key.keyOps())); } } else { key = null; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java index bad0b37d43b75..6d62c41fc166f 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java @@ -8,6 +8,7 @@ import com.microsoft.azure.keyvault.KeyIdentifier; import com.microsoft.azure.keyvault.models.Attributes; import com.microsoft.azure.keyvault.models.KeyAttributes; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; /** * The key update request class. @@ -17,7 +18,7 @@ public final class UpdateKeyRequest { private final String vaultBaseUrl; private final String keyName; private final String keyVersion; - private final List keyOperations; + private final List keyOperations; private final KeyAttributes keyAttributes; private final Map tags; @@ -32,7 +33,7 @@ public static class Builder { // Optional parameters private String keyVersion; - private List keyOperations; + private List keyOperations; private KeyAttributes attributes; private Map tags; @@ -83,7 +84,7 @@ public Builder withVersion(String keyVersion) { * the key operation list * @return the Builder object itself. */ - public Builder withKeyOperations(List keyOperations) { + public Builder withKeyOperations(List keyOperations) { this.keyOperations = keyOperations; return this; } @@ -129,7 +130,7 @@ private UpdateKeyRequest(Builder builder) { keyVersion = builder.keyVersion == null ? "" : builder.keyVersion; if (builder.keyOperations != null) { - keyOperations = new ArrayList(builder.keyOperations); + keyOperations = new ArrayList(builder.keyOperations); } else { keyOperations = null; } @@ -172,7 +173,7 @@ public String keyVersion() { /** * @return the key operations */ - public List keyOperations() { + public List keyOperations() { return keyOperations; } diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java index 44eb04f681b56..3fcd6787ce999 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -46,6 +46,7 @@ import com.microsoft.azure.keyvault.requests.UpdateSecretRequest; import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; public class AsyncOperationsTest extends KeyVaultClientIntegrationTestBase { @@ -56,7 +57,7 @@ public void keyAsync() throws Exception { String vault = getVaultUri(); String keyname = "mykey"; - CreateKeyRequest createKeyRequest = new CreateKeyRequest.Builder(vault, keyname, "RSA").build(); + CreateKeyRequest createKeyRequest = new CreateKeyRequest.Builder(vault, keyname, JsonWebKeyType.RSA).build(); KeyBundle keyBundle = keyVaultClient.createKeyAsync(createKeyRequest, null).get().getBody(); Assert.assertNotNull(keyBundle); @@ -81,16 +82,16 @@ public void keyAsync() throws Exception { KeyBundle restoreResult = keyVaultClient.restoreKeyAsync(vault, backupResult.value(), null).get().getBody(); Assert.assertNotNull(restoreResult); - KeyOperationResult encryptResult = keyVaultClient.encryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, new byte[100], null).get().getBody(); + KeyOperationResult encryptResult = keyVaultClient.encryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, new byte[100], null).get().getBody(); Assert.assertNotNull(encryptResult); - KeyOperationResult decryptResult = keyVaultClient.decryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, encryptResult.result(), null).get().getBody(); + KeyOperationResult decryptResult = keyVaultClient.decryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, encryptResult.result(), null).get().getBody(); Assert.assertNotNull(decryptResult); - KeyOperationResult wrapResult = keyVaultClient.wrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, new byte[100], null).get().getBody(); + KeyOperationResult wrapResult = keyVaultClient.wrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, new byte[100], null).get().getBody(); Assert.assertNotNull(wrapResult); - KeyOperationResult unwrapResult = keyVaultClient.unwrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, wrapResult.result(), null).get().getBody(); + KeyOperationResult unwrapResult = keyVaultClient.unwrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, wrapResult.result(), null).get().getBody(); Assert.assertNotNull(unwrapResult); byte[] plainText = new byte[100]; diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java index 3af77cfca2625..c3dfd810293e3 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -677,9 +677,11 @@ public void listCertificates() throws Exception { HashSet toDelete = new HashSet(); for (CertificateItem item : listResult) { - CertificateIdentifier id = new CertificateIdentifier(item.id()); - toDelete.add(id.name()); - certificates.remove(item.id()); + if(item != null) { + CertificateIdentifier id = new CertificateIdentifier(item.id()); + toDelete.add(id.name()); + certificates.remove(item.id()); + } } Assert.assertEquals(0, certificates.size()); @@ -736,7 +738,9 @@ public void listCertificateVersions() throws Exception { listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName).getBody(); for (CertificateItem item : listResult) { - certificates.remove(item.id()); + if(item != null) { + certificates.remove(item.id()); + } } Assert.assertEquals(0, certificates.size()); diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java index 54eb89cd3d444..92de113eb9f98 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -56,28 +56,28 @@ public void transparentAuthentication() throws Exception { { Map tags = new HashMap(); tags.put("foo", "baz"); - List keyOps = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); + List keyOps = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); Attributes attribute = new KeyAttributes() .withEnabled(true) .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest - .Builder(getVaultUri(), KEY_NAME, "RSA") + .Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA) .withAttributes(attribute) .withKeyOperations(keyOps) .withKeySize(2048) .withTags(tags) .build()).getBody(); - validateRsaKeyBundle(bundle, getVaultUri(), KEY_NAME, "RSA", keyOps, attribute); + validateRsaKeyBundle(bundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, keyOps, attribute); } // Create a key on a different vault. Key Vault Data Plane returns 401, // which must be transparently handled by KeyVaultCredentials. { - KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getSecondaryVaultUri(), KEY_NAME, "RSA").build()).getBody(); - validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, "RSA", null, null); + KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()).getBody(); + validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } } @@ -114,7 +114,7 @@ private void checkImportOperation(KeyBundle keyBundle, boolean importToHardware) .withTags(tags) .build()).getBody(); - validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? "RSA-HSM" : "RSA", importedJwk.keyOps(), attribute); + validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? JsonWebKeyType.RSA_HSM : JsonWebKeyType.RSA, importedJwk.keyOps(), attribute); checkEncryptDecryptSequence(importedJwk, importResultBundle); } @@ -127,7 +127,7 @@ private void checkEncryptDecryptSequence(JsonWebKey importedKey, KeyBundle impor // Encrypt in the service. { - KeyOperationResult result = keyVaultClient.encrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + KeyOperationResult result = keyVaultClient.encrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); cipherText = result.result(); } @@ -152,7 +152,7 @@ private void checkEncryptDecryptSequence(JsonWebKey importedKey, KeyBundle impor // Decrypt in the service. { - KeyOperationResult result = keyVaultClient.decrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA15, cipherText).getBody(); + KeyOperationResult result = keyVaultClient.decrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA1_5, cipherText).getBody(); byte[] beforeEncrypt = plainText; byte[] afterDecrypt = result.result(); @@ -166,8 +166,8 @@ public void crudOperations() throws Exception { KeyBundle createdBundle; { // Create key - createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA").build()).getBody(); - validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, "RSA", null, null); + createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()).getBody(); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } // Key identifier. @@ -211,7 +211,7 @@ public void crudOperations() throws Exception { .withMonthOfYear(2) .withDayOfMonth(1) .withYear(2050)); - List key_ops = Arrays.asList("encrypt", "decrypt"); + List key_ops = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); Map tags = new HashMap(); tags.put("foo", "baz"); createdBundle.key().withKeyOps(key_ops); @@ -240,7 +240,7 @@ public void crudOperations() throws Exception { .withMonthOfYear(2) .withDayOfMonth(1) .withYear(2000)); - List key_ops = Arrays.asList("sign", "verify"); + List key_ops = Arrays.asList(JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY); createdBundle.key().withKeyOps(key_ops); Map tags = new HashMap(); tags.put("foo", "baz"); @@ -284,9 +284,9 @@ public void backupRestore() throws Exception { // Creates a key { createdBundle = keyVaultClient.createKey( - new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA") + new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA) .build()).getBody(); - validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, "RSA", null, null); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } // Creates a backup of key. @@ -316,7 +316,7 @@ public void listKeys() throws Exception { int failureCount = 0; for (;;) { try { - KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME + i, "RSA").build()).getBody(); + KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME + i, JsonWebKeyType.RSA).build()).getBody(); KeyIdentifier kid = new KeyIdentifier(createdBundle.key().kid()); keys.add(kid.baseIdentifier()); break; @@ -338,9 +338,11 @@ public void listKeys() throws Exception { HashSet toDelete = new HashSet(); for (KeyItem item : listResult) { - KeyIdentifier id = new KeyIdentifier(item.kid()); - toDelete.add(id.name()); - keys.remove(item.kid()); + if(item != null) { + KeyIdentifier id = new KeyIdentifier(item.kid()); + toDelete.add(id.name()); + keys.remove(item.kid()); + } } Assert.assertEquals(0, keys.size()); @@ -365,7 +367,7 @@ public void listKeyVersions() throws Exception { int failureCount = 0; for (;;) { try { - KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, "RSA").build()).getBody(); + KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()).getBody(); keys.add(createdBundle.key().kid()); break; } catch (KeyVaultErrorException e) { @@ -386,7 +388,9 @@ public void listKeyVersions() throws Exception { listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME).getBody(); for (KeyItem item : listResult) { - keys.remove(item.kid()); + if(item != null) { + keys.remove(item.kid()); + } } Assert.assertEquals(0, keys.size()); @@ -409,19 +413,19 @@ public void encryptDecryptOperations() throws Exception { // encrypt and decrypt using kid WO version { - result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); cipherText = result.result(); - result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); + result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); Assert.assertArrayEquals(plainText, result.result()); } // encrypt and decrypt using full kid { - result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); cipherText = result.result(); - result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); + result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); Assert.assertArrayEquals(plainText, result.result()); } } @@ -441,19 +445,19 @@ public void wrapUnwrapOperations() throws Exception { // wrap and unwrap using kid WO version { - result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); cipherText = result.result(); - result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); + result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); Assert.assertArrayEquals(plainText, result.result()); } // wrap and unwrap using full kid { - result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); cipherText = result.result(); - result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); + result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); Assert.assertArrayEquals(plainText, result.result()); } } @@ -501,7 +505,7 @@ private static JsonWebKey importTestKey() throws Exception { JsonWebKey key = JsonWebKey.fromRSA(getTestKeyMaterial()); key.withKty(JsonWebKeyType.RSA); - key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT, JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY, JsonWebKeyOperation.WRAP, JsonWebKeyOperation.UNWRAP)); + key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT, JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY, JsonWebKeyOperation.WRAP_KEY, JsonWebKeyOperation.UNWRAP_KEY)); keyBundle = keyVaultClient.importKey( new ImportKeyRequest @@ -509,7 +513,7 @@ private static JsonWebKey importTestKey() throws Exception { .withHsm(false) .build()).getBody(); - validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, "RSA", null, null); + validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); return keyBundle.key(); } @@ -535,7 +539,7 @@ private static KeyPair getWellKnownKey() throws Exception { return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); } - private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, String kty, List key_ops, Attributes attributes) throws Exception { + private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, JsonWebKeyType kty, List key_ops, Attributes attributes) throws Exception { String prefix = vault + "/keys/" + keyName + "/"; String kid = bundle.key().kid(); Assert.assertTrue( diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java index af27ec8973c2f..ed6282decdf41 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java @@ -174,8 +174,7 @@ public void crudOperations() throws Exception { } @Test - public void listSecrets() throws Exception { - + public void listSecrets() throws Exception { HashSet secrets = new HashSet(); for (int i = 0; i < MAX_SECRETS; ++i) { int failureCount = 0; @@ -204,9 +203,11 @@ public void listSecrets() throws Exception { HashSet toDelete = new HashSet(); for (SecretItem item : listResult) { - SecretIdentifier id = new SecretIdentifier(item.id()); - toDelete.add(id.name()); - secrets.remove(item.id()); + if(item != null) { + SecretIdentifier id = new SecretIdentifier(item.id()); + toDelete.add(id.name()); + secrets.remove(item.id()); + } } Assert.assertEquals(0, secrets.size()); @@ -252,7 +253,9 @@ public void listSecretVersions() throws Exception { listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME).getBody(); for (SecretItem item : listResult) { - secrets.remove(item.id()); + if(item != null) { + secrets.remove(item.id()); + } } Assert.assertEquals(0, secrets.size()); From b4bfac80cd723b456f504589c3bf953b46ecb101 Mon Sep 17 00:00:00 2001 From: Pooneh Date: Fri, 2 Sep 2016 11:47:41 -0700 Subject: [PATCH 11/14] fix styling errors and addressed feedback. --- .../webkey/Base64UrlJsonDeserializer.java | 4 ++-- .../webkey/Base64UrlJsonSerializer.java | 4 ++-- .../azure/keyvault/webkey/JsonWebKey.java | 2 +- .../azure/keyvault/KeyVaultClient.java | 1 - .../azure/keyvault/KeyVaultClientImpl.java | 2 -- .../authentication/ChallengeCache.java | 5 +--- .../models/KeyVaultErrorException.java | 7 +++--- .../requests/SetCertificateIssuerRequest.java | 6 ++--- .../UpdateCertificateIssuerRequest.java | 23 ++++++++++++++----- .../keyvault/test/AsyncOperationsTest.java | 2 +- .../test/CertificateOperationsTest.java | 3 ++- 11 files changed, 32 insertions(+), 27 deletions(-) diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java index 18967a8863809..9418b15a96736 100644 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java @@ -20,13 +20,13 @@ */ public class Base64UrlJsonDeserializer extends JsonDeserializer { - static final Base64 _base64 = new Base64(-1, null, true); + static final Base64 BASE64 = new Base64(-1, null, true); @Override public byte[] deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String text = jp.getText(); if (text != null) { - return _base64.decode(text); + return BASE64.decode(text); } return null; } diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java index 3613a1aa79199..eac3d33e26c7b 100644 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java @@ -20,7 +20,7 @@ */ public class Base64UrlJsonSerializer extends JsonSerializer { - static final Base64 _base64 = new Base64(-1, null, true); + static final Base64 BASE64 = new Base64(-1, null, true); @Override public void serialize(byte[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { @@ -30,7 +30,7 @@ public void serialize(byte[] value, JsonGenerator jgen, SerializerProvider provi } else if (value.length == 0) { text = ""; } else { - text = _base64.encodeAsString(value); + text = BASE64.encodeAsString(value); } jgen.writeString(text); } diff --git a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java index 868cab9204858..5d6dc8fe8b355 100755 --- a/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java @@ -245,7 +245,7 @@ public byte[] dp() { } /** - * Set RSA Private Key Parameter value + * Set RSA Private Key Parameter value. * @param dp the RSA Private Key Parameter value to set. * @return the JsonWebKey object itself. */ diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java index 0dbb76b43010b..95a998e02c63b 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java @@ -50,7 +50,6 @@ import com.microsoft.rest.credentials.ServiceClientCredentials; import okhttp3.ResponseBody; -import retrofit2.Call; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Header; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java index 156945410742d..ddeb203106bf6 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java @@ -59,8 +59,6 @@ import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; -import com.microsoft.azure.keyvault.webkey.Base64UrlJsonSerializer; -import com.microsoft.azure.keyvault.webkey.Base64UrlJsonDeserializer; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java index 07cd0a8dc49b7..a0700600afffe 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java @@ -10,13 +10,10 @@ import java.util.Locale; import java.util.Map; -import com.microsoft.rest.credentials.ServiceClientCredentials; - import okhttp3.HttpUrl; /** - * An implementation of {@link ServiceClientCredentials} that supports automatic bearer token refresh. - * + * Handles caching of the challenge. */ class ChallengeCache { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java index 43b6a45e162db..796e35e8da3c6 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java @@ -31,14 +31,13 @@ public class KeyVaultErrorException extends RestException { public KeyVaultErrorException() { } @Override - public String getMessage() - { - if(body != null && body.error() != null + public String getMessage() { + if (body != null && body.error() != null && body.error().message() != null && !body.error().message().isEmpty()) { return body.error().message(); } - return getMessage(); + return super.getMessage(); } /** * Initializes a new instance of the KeyVaultErrorException class. diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java index 23201a4a26f4a..7d582e2f5bde6 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java @@ -77,7 +77,7 @@ public Builder withOrganizationDetails(OrganizationDetails organizationDetails) /** * Set issuer attributes. * - * @param organizationDetails + * @param attributes * The issuer attributes. * @return the Builder object itself. */ @@ -100,14 +100,14 @@ private SetCertificateIssuerRequest(Builder builder) { vaultBaseUrl = builder.vaultBaseUrl; issuerName = builder.issuerName; provider = builder.provider; - if(builder.organizationDetails != null) { + if (builder.organizationDetails != null) { organizationDetails = new OrganizationDetails() .withId(builder.organizationDetails.id()) .withAdminDetails(new ArrayList(builder.organizationDetails.adminDetails())); } else { organizationDetails = null; } - if(builder.credentials != null) { + if (builder.credentials != null) { credentials = new IssuerCredentials() .withAccountId(builder.credentials.accountId()) .withPassword(builder.credentials.password()); diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java index 37d1048673aea..d743f86cabe6c 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java @@ -26,9 +26,9 @@ public static class Builder { // Required parameters private final String vaultBaseUrl; private final String issuerName; - private final String provider; // Optional parameters + private String provider; private IssuerCredentials credentials; private OrganizationDetails organizationDetails; private IssuerAttributes attributes; @@ -42,12 +42,23 @@ public static class Builder { * @param issuerName * The name of the issuer in the given vault. */ - public Builder(String vaultBaseUrl, String issuerName, String provider) { + public Builder(String vaultBaseUrl, String issuerName) { this.vaultBaseUrl = vaultBaseUrl; this.issuerName = issuerName; - this.provider = provider; } + /** + * Set issuer credentials. + * + * @param provider + * The issuer provider. + * @return the Builder object itself. + */ + public Builder withProvider(String provider) { + this.provider = provider; + return this; + } + /** * Set issuer credentials. * @@ -75,7 +86,7 @@ public Builder withOrganizationDetails(OrganizationDetails organizationDetails) /** * Set issuer attributes. * - * @param organizationDetails + * @param attributes * The issuer attributes. * @return the Builder object itself. */ @@ -98,14 +109,14 @@ private UpdateCertificateIssuerRequest(Builder builder) { vaultBaseUrl = builder.vaultBaseUrl; issuerName = builder.issuerName; provider = builder.provider; - if(builder.organizationDetails != null) { + if (builder.organizationDetails != null) { organizationDetails = new OrganizationDetails() .withId(builder.organizationDetails.id()) .withAdminDetails(new ArrayList(builder.organizationDetails.adminDetails())); } else { organizationDetails = null; } - if(builder.credentials != null) { + if (builder.credentials != null) { credentials = new IssuerCredentials() .withAccountId(builder.credentials.accountId()) .withPassword(builder.credentials.password()); diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java index 3fcd6787ce999..c2277e5bf2c5d 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -241,7 +241,7 @@ public void issuerAsync() throws Exception { IssuerBundle certificateIssuer = keyVaultClient.setCertificateIssuerAsync(setCertificateIssuerRequest, null).get().getBody(); Assert.assertNotNull(certificateIssuer); - UpdateCertificateIssuerRequest updateCertificateIssuerRequest = new UpdateCertificateIssuerRequest.Builder(vault, issuerName, "SslAdmin").build(); + UpdateCertificateIssuerRequest updateCertificateIssuerRequest = new UpdateCertificateIssuerRequest.Builder(vault, issuerName).withProvider("SslAdmin").build(); certificateIssuer = keyVaultClient.updateCertificateIssuerAsync(updateCertificateIssuerRequest, null).get().getBody(); Assert.assertNotNull(certificateIssuer); diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java index c3dfd810293e3..8e4b7c7dced0f 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -798,7 +798,8 @@ public void issuerCrudOperations() throws Exception { retrievedCertificateIssuer.withCredentials(updatedCredentials); IssuerBundle updatedCertificateIssuer = keyVaultClient.updateCertificateIssuer( new UpdateCertificateIssuerRequest - .Builder(getVaultUri(), certificateIssuerName, ISSUER_TEST) + .Builder(getVaultUri(), certificateIssuerName) + .withProvider(ISSUER_TEST) .withCredentials(updatedCredentials) .withOrganizationDetails(retrievedCertificateIssuer.organizationDetails()) .withAttributes(retrievedCertificateIssuer.attributes()) From 26132d734f88ca046c18ae25305cef5a3a59f76b Mon Sep 17 00:00:00 2001 From: Pooneh Date: Fri, 9 Sep 2016 10:20:01 -0700 Subject: [PATCH 12/14] Remove .getBody for ListanableFuture to accomodate the recent breaking change --- .../keyvault/extensions/KeyVaultKey.java | 19 +++-- .../extensions/KeyVaultKeyResolver.java | 15 ++-- .../keyvault/test/AsyncOperationsTest.java | 78 +++++++++---------- 3 files changed, 54 insertions(+), 58 deletions(-) diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java index f4afd66b74aaa..d3bf97abc148b 100755 --- a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java @@ -35,7 +35,6 @@ import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyOperationResult; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; -import com.microsoft.rest.ServiceResponse; /** * The key vault key that performs cryptography operations. @@ -45,22 +44,22 @@ public class KeyVaultKey implements IKey { /** * Transforms the result of decrypt operation to byte array. */ - class DecryptResultTransform implements Function, byte[]> { + class DecryptResultTransform implements Function { DecryptResultTransform() { super(); } @Override - public byte[] apply(ServiceResponse result) { - return result.getBody().result(); + public byte[] apply(KeyOperationResult result) { + return result.result(); } } /** * Transforms the result of sign operation to byte array and algorithm pair. */ - class SignResultTransform implements Function, Pair> { + class SignResultTransform implements Function> { private final String algorithm; @@ -70,9 +69,9 @@ class SignResultTransform implements Function apply(ServiceResponse input) { + public Pair apply(KeyOperationResult input) { - return Pair.of(input.getBody().result(), algorithm); + return Pair.of(input.result(), algorithm); } } @@ -168,7 +167,7 @@ public ListenableFuture decryptAsync(byte[] ciphertext, byte[] iv, byte[ } // Never local - ListenableFuture> futureCall = + ListenableFuture futureCall = client.decryptAsync( implementation.getKid(), new JsonWebKeyEncryptionAlgorithm(algorithm), @@ -206,7 +205,7 @@ public ListenableFuture unwrapKeyAsync(byte[] ciphertext, String algorit } // Never local - ListenableFuture> futureCall = + ListenableFuture futureCall = client.unwrapKeyAsync( implementation.getKid(), new JsonWebKeyEncryptionAlgorithm(algorithm), @@ -226,7 +225,7 @@ public ListenableFuture> signAsync(byte[] digest, String al } // Never local - ListenableFuture> futureCall = + ListenableFuture futureCall = client.signAsync( implementation.getKid(), new JsonWebKeySignatureAlgorithm(algorithm), diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java index 92f66ddba0c50..7f8e778ef0681 100755 --- a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java @@ -32,7 +32,6 @@ import com.microsoft.azure.keyvault.cryptography.SymmetricKey; import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.SecretBundle; -import com.microsoft.rest.ServiceResponse; /** * The key resolver class that handles resolving key id to type {@link IKey} @@ -45,16 +44,15 @@ public class KeyVaultKeyResolver implements IKeyResolver { /** * Transforms {@link KeyBundle} to {@link IKey}. */ - class FutureKeyFromKey implements Function, IKey> { + class FutureKeyFromKey implements Function { protected FutureKeyFromKey() { super(); } @Override - public IKey apply(ServiceResponse keyBundleResponse) { + public IKey apply(KeyBundle keyBundle) { - KeyBundle keyBundle = keyBundleResponse.getBody(); if (keyBundle != null) { return new KeyVaultKey(client, keyBundle); } @@ -66,16 +64,15 @@ public IKey apply(ServiceResponse keyBundleResponse) { /** * Transforms {@link SecretBundle} to {@link IKey}. */ - class FutureKeyFromSecret implements Function, IKey> { + class FutureKeyFromSecret implements Function { protected FutureKeyFromSecret() { super(); } @Override - public IKey apply(ServiceResponse secretBundleResponse) { + public IKey apply(SecretBundle secretBundle) { - SecretBundle secretBundle = secretBundleResponse.getBody(); if (secretBundle != null && secretBundle.contentType().equalsIgnoreCase("application/octet-stream")) { byte[] keyBytes = BASE64.decode(secretBundle.value()); @@ -112,13 +109,13 @@ public KeyVaultKeyResolver(KeyVaultClient client, Provider provider) { private ListenableFuture resolveKeyFromSecretAsync(String kid) { - ListenableFuture> futureCall = client.getSecretAsync(kid, null); + ListenableFuture futureCall = client.getSecretAsync(kid, null); return Futures.transform(futureCall, new FutureKeyFromSecret()); } private ListenableFuture resolveKeyFromKeyAsync(String kid) { - ListenableFuture> futureCall = client.getKeyAsync(kid, null); + ListenableFuture futureCall = client.getKeyAsync(kid, null); return Futures.transform(futureCall, new FutureKeyFromKey()); } diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java index c2277e5bf2c5d..878603707842f 100644 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -58,40 +58,40 @@ public void keyAsync() throws Exception { String keyname = "mykey"; CreateKeyRequest createKeyRequest = new CreateKeyRequest.Builder(vault, keyname, JsonWebKeyType.RSA).build(); - KeyBundle keyBundle = keyVaultClient.createKeyAsync(createKeyRequest, null).get().getBody(); + KeyBundle keyBundle = keyVaultClient.createKeyAsync(createKeyRequest, null).get(); Assert.assertNotNull(keyBundle); UpdateKeyRequest updateKeyRequest = new UpdateKeyRequest.Builder(keyBundle.key().kid()).build(); - keyBundle = keyVaultClient.updateKeyAsync(updateKeyRequest, null).get().getBody(); + keyBundle = keyVaultClient.updateKeyAsync(updateKeyRequest, null).get(); Assert.assertNotNull(keyBundle); - keyBundle = keyVaultClient.getKeyAsync(keyBundle.key().kid(), null).get().getBody(); + keyBundle = keyVaultClient.getKeyAsync(keyBundle.key().kid(), null).get(); Assert.assertNotNull(keyBundle); - List keyItems = keyVaultClient.listKeysAsync(vault, 2, null).get().getBody(); + List keyItems = keyVaultClient.listKeysAsync(vault, 2, null).get(); Assert.assertNotNull(keyItems); - List keyVersionItems = keyVaultClient.listKeyVersionsAsync(getVaultUri(), keyname, 2, null).get().getBody(); + List keyVersionItems = keyVaultClient.listKeyVersionsAsync(getVaultUri(), keyname, 2, null).get(); Assert.assertNotNull(keyVersionItems); - BackupKeyResult backupResult = keyVaultClient.backupKeyAsync(vault, keyname, null).get().getBody(); + BackupKeyResult backupResult = keyVaultClient.backupKeyAsync(vault, keyname, null).get(); Assert.assertNotNull(backupResult); keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get(); - KeyBundle restoreResult = keyVaultClient.restoreKeyAsync(vault, backupResult.value(), null).get().getBody(); + KeyBundle restoreResult = keyVaultClient.restoreKeyAsync(vault, backupResult.value(), null).get(); Assert.assertNotNull(restoreResult); - KeyOperationResult encryptResult = keyVaultClient.encryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, new byte[100], null).get().getBody(); + KeyOperationResult encryptResult = keyVaultClient.encryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, new byte[100], null).get(); Assert.assertNotNull(encryptResult); - KeyOperationResult decryptResult = keyVaultClient.decryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, encryptResult.result(), null).get().getBody(); + KeyOperationResult decryptResult = keyVaultClient.decryptAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, encryptResult.result(), null).get(); Assert.assertNotNull(decryptResult); - KeyOperationResult wrapResult = keyVaultClient.wrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, new byte[100], null).get().getBody(); + KeyOperationResult wrapResult = keyVaultClient.wrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, new byte[100], null).get(); Assert.assertNotNull(wrapResult); - KeyOperationResult unwrapResult = keyVaultClient.unwrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, wrapResult.result(), null).get().getBody(); + KeyOperationResult unwrapResult = keyVaultClient.unwrapKeyAsync(keyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, wrapResult.result(), null).get(); Assert.assertNotNull(unwrapResult); byte[] plainText = new byte[100]; @@ -99,13 +99,13 @@ public void keyAsync() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(plainText); byte[] digest = md.digest(); - KeyOperationResult signResult = keyVaultClient.signAsync(keyBundle.key().kid(), JsonWebKeySignatureAlgorithm.RS256, digest, null).get().getBody(); + KeyOperationResult signResult = keyVaultClient.signAsync(keyBundle.key().kid(), JsonWebKeySignatureAlgorithm.RS256, digest, null).get(); Assert.assertNotNull(signResult); - KeyVerifyResult verifypResult = keyVaultClient.verifyAsync(keyBundle.key().kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signResult.result(), null).get().getBody(); + KeyVerifyResult verifypResult = keyVaultClient.verifyAsync(keyBundle.key().kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signResult.result(), null).get(); Assert.assertTrue(verifypResult.value()); - keyBundle = keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get().getBody(); + keyBundle = keyVaultClient.deleteKeyAsync(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name(), null).get(); Assert.assertNotNull(keyBundle); //Get the unavailable key to throw exception -> it gets stuck @@ -131,23 +131,23 @@ public void secretAsync() throws Exception { String password = "password"; SetSecretRequest setSecretRequest = new SetSecretRequest.Builder(vault, secretname, password).build(); - SecretBundle secretBundle = keyVaultClient.setSecretAsync(setSecretRequest, null).get().getBody(); + SecretBundle secretBundle = keyVaultClient.setSecretAsync(setSecretRequest, null).get(); Assert.assertNotNull(secretBundle); UpdateSecretRequest updateSecretRequest = new UpdateSecretRequest.Builder(secretBundle.id()).build(); - secretBundle = keyVaultClient.updateSecretAsync(updateSecretRequest, null).get().getBody(); + secretBundle = keyVaultClient.updateSecretAsync(updateSecretRequest, null).get(); Assert.assertNotNull(secretBundle); - secretBundle = keyVaultClient.getSecretAsync(secretBundle.id(), null).get().getBody(); + secretBundle = keyVaultClient.getSecretAsync(secretBundle.id(), null).get(); Assert.assertNotNull(secretBundle); - List secretItems = keyVaultClient.listSecretsAsync(vault, 2, null).get().getBody(); + List secretItems = keyVaultClient.listSecretsAsync(vault, 2, null).get(); Assert.assertNotNull(secretItems); - List secretVersionItems = keyVaultClient.listSecretVersionsAsync(vault, secretname, 2, null).get().getBody(); + List secretVersionItems = keyVaultClient.listSecretVersionsAsync(vault, secretname, 2, null).get(); Assert.assertNotNull(secretVersionItems); - secretBundle = keyVaultClient.deleteSecretAsync(vault, secretname, null).get().getBody(); + secretBundle = keyVaultClient.deleteSecretAsync(vault, secretname, null).get(); Assert.assertNotNull(secretBundle); try { @@ -179,44 +179,44 @@ public void certificateAsync() throws Exception { .withSubject("CN=SelfSignedJavaPkcs12") .withValidityInMonths(12))) .build(); - CertificateOperation certificateOperation = keyVaultClient.createCertificateAsync(createCertificateRequest, null).get().getBody(); + CertificateOperation certificateOperation = keyVaultClient.createCertificateAsync(createCertificateRequest, null).get(); Assert.assertNotNull(certificateOperation); UpdateCertificateOperationRequest updateCertificateOperationRequest = new UpdateCertificateOperationRequest.Builder(vault, certificateName, false).build(); - certificateOperation = keyVaultClient.updateCertificateOperationAsync(updateCertificateOperationRequest, null).get().getBody(); + certificateOperation = keyVaultClient.updateCertificateOperationAsync(updateCertificateOperationRequest, null).get(); Assert.assertNotNull(certificateOperation); Map tags = new HashMap(); tags.put("tag1", "foo"); UpdateCertificateRequest updateCertificateRequest = new UpdateCertificateRequest.Builder(vault, certificateName).withTags(tags).build(); - CertificateBundle certificateBundle = keyVaultClient.updateCertificateAsync(updateCertificateRequest, null).get().getBody(); + CertificateBundle certificateBundle = keyVaultClient.updateCertificateAsync(updateCertificateRequest, null).get(); Assert.assertNotNull(certificateBundle); UpdateCertificatePolicyRequest updateCertificatePolicyRequest = new UpdateCertificatePolicyRequest.Builder(vault, certificateName).build(); - CertificatePolicy certificatePolicy = keyVaultClient.updateCertificatePolicyAsync(updateCertificatePolicyRequest, null).get().getBody(); + CertificatePolicy certificatePolicy = keyVaultClient.updateCertificatePolicyAsync(updateCertificatePolicyRequest, null).get(); Assert.assertNotNull(certificatePolicy); - certificatePolicy = keyVaultClient.getCertificatePolicyAsync(vault, certificateName, null).get().getBody(); + certificatePolicy = keyVaultClient.getCertificatePolicyAsync(vault, certificateName, null).get(); Assert.assertNotNull(certificatePolicy); - certificateOperation = keyVaultClient.getCertificateOperationAsync(vault, certificateName, null).get().getBody(); + certificateOperation = keyVaultClient.getCertificateOperationAsync(vault, certificateName, null).get(); Assert.assertNotNull(certificateOperation); - certificateBundle = keyVaultClient.getCertificateAsync(vault, certificateName, null).get().getBody(); + certificateBundle = keyVaultClient.getCertificateAsync(vault, certificateName, null).get(); Assert.assertNotNull(certificateBundle); - String cert = keyVaultClient.getPendingCertificateSigningRequestAsync(vault, certificateName, null).get().getBody(); + String cert = keyVaultClient.getPendingCertificateSigningRequestAsync(vault, certificateName, null).get(); Assert.assertTrue(!cert.isEmpty()); - List certificateItem = keyVaultClient.listCertificatesAsync(vault, null).get().getBody(); + List certificateItem = keyVaultClient.listCertificatesAsync(vault, null).get(); Assert.assertNotNull(certificateItem); - List certificateVersionItem = keyVaultClient.listCertificateVersionsAsync(vault, certificateName, null).get().getBody(); + List certificateVersionItem = keyVaultClient.listCertificateVersionsAsync(vault, certificateName, null).get(); Assert.assertNotNull(certificateVersionItem); - keyVaultClient.deleteCertificateOperationAsync(vault, certificateName, null).get().getBody(); - keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get().getBody(); + keyVaultClient.deleteCertificateOperationAsync(vault, certificateName, null).get(); + keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get(); try { keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get(); @@ -238,20 +238,20 @@ public void issuerAsync() throws Exception { String issuerName = "myIssuer"; SetCertificateIssuerRequest setCertificateIssuerRequest = new SetCertificateIssuerRequest.Builder(vault, issuerName, "Test").build(); - IssuerBundle certificateIssuer = keyVaultClient.setCertificateIssuerAsync(setCertificateIssuerRequest, null).get().getBody(); + IssuerBundle certificateIssuer = keyVaultClient.setCertificateIssuerAsync(setCertificateIssuerRequest, null).get(); Assert.assertNotNull(certificateIssuer); UpdateCertificateIssuerRequest updateCertificateIssuerRequest = new UpdateCertificateIssuerRequest.Builder(vault, issuerName).withProvider("SslAdmin").build(); - certificateIssuer = keyVaultClient.updateCertificateIssuerAsync(updateCertificateIssuerRequest, null).get().getBody(); + certificateIssuer = keyVaultClient.updateCertificateIssuerAsync(updateCertificateIssuerRequest, null).get(); Assert.assertNotNull(certificateIssuer); - certificateIssuer = keyVaultClient.getCertificateIssuerAsync(vault, issuerName, null).get().getBody(); + certificateIssuer = keyVaultClient.getCertificateIssuerAsync(vault, issuerName, null).get(); Assert.assertNotNull(certificateIssuer); - List issuers = keyVaultClient.listCertificateIssuersAsync(vault, null).get().getBody(); + List issuers = keyVaultClient.listCertificateIssuersAsync(vault, null).get(); Assert.assertNotNull(issuers); - keyVaultClient.deleteCertificateIssuerAsync(vault, issuerName, null).get().getBody(); + keyVaultClient.deleteCertificateIssuerAsync(vault, issuerName, null).get(); } @@ -260,10 +260,10 @@ public void certificateContactsAsync() throws Exception { String vault = getVaultUri(); - Contacts contacts = keyVaultClient.setCertificateContactsAsync(vault, new Contacts(), null).get().getBody(); + Contacts contacts = keyVaultClient.setCertificateContactsAsync(vault, new Contacts(), null).get(); Assert.assertNotNull(contacts); - contacts = keyVaultClient.getCertificateContactsAsync(vault, null).get().getBody(); + contacts = keyVaultClient.getCertificateContactsAsync(vault, null).get(); Assert.assertNotNull(contacts); keyVaultClient.deleteCertificateContactsAsync(vault, null).get(); From c9bce2e40fd9811bd6aa9cb22536b5fff6a4eb76 Mon Sep 17 00:00:00 2001 From: Pooneh Date: Mon, 12 Sep 2016 10:30:25 -0700 Subject: [PATCH 13/14] key vault cryptography refactoring. Removing additional methods from ByteExtension and using Arrays extension methods where applicable. Changed static final names to all caps. --- .../cryptography/AlgorithmResolver.java | 26 ++--- .../keyvault/cryptography/ByteExtensions.java | 95 ++----------------- .../azure/keyvault/cryptography/RsaKey.java | 8 +- .../keyvault/cryptography/SymmetricKey.java | 20 ++-- .../cryptography/algorithms/Aes128Cbc.java | 57 +---------- .../algorithms/Aes128CbcHmacSha256.java | 4 +- .../cryptography/algorithms/Aes192Cbc.java | 58 +---------- .../algorithms/Aes192CbcHmacSha384.java | 4 +- .../cryptography/algorithms/Aes256Cbc.java | 58 +---------- .../algorithms/Aes256CbcHmacSha512.java | 4 +- .../cryptography/algorithms/AesCbc.java | 33 +++++-- .../algorithms/AesCbcHmacSha2.java | 6 +- .../cryptography/algorithms/AesKw128.java | 10 +- .../cryptography/algorithms/AesKw192.java | 10 +- .../cryptography/algorithms/AesKw256.java | 10 +- .../cryptography/algorithms/Rs256.java | 26 ++++- .../cryptography/algorithms/Rsa15.java | 4 +- .../cryptography/algorithms/RsaOaep.java | 4 +- .../cryptography/test/AesCbcTest.java | 18 ++-- .../cryptography/test/RsaKeyTest.java | 26 ++--- 20 files changed, 144 insertions(+), 337 deletions(-) diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java index 6804aa055420d..60930c8d1e3a7 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java @@ -27,23 +27,23 @@ public class AlgorithmResolver { public static final AlgorithmResolver Default = new AlgorithmResolver(); static { - Default.put(Aes128CbcHmacSha256.AlgorithmName, new Aes128CbcHmacSha256()); - Default.put(Aes192CbcHmacSha384.AlgorithmName, new Aes192CbcHmacSha384()); - Default.put(Aes256CbcHmacSha512.AlgorithmName, new Aes256CbcHmacSha512()); + Default.put(Aes128CbcHmacSha256.ALGORITHM_NAME, new Aes128CbcHmacSha256()); + Default.put(Aes192CbcHmacSha384.ALGORITHM_NAME, new Aes192CbcHmacSha384()); + Default.put(Aes256CbcHmacSha512.ALGORITHM_NAME, new Aes256CbcHmacSha512()); - Default.put(Aes128Cbc.AlgorithmName, new Aes128Cbc()); - Default.put(Aes192Cbc.AlgorithmName, new Aes192Cbc()); - Default.put(Aes256Cbc.AlgorithmName, new Aes256Cbc()); + Default.put(Aes128Cbc.ALGORITHM_NAME, new Aes128Cbc()); + Default.put(Aes192Cbc.ALGORITHM_NAME, new Aes192Cbc()); + Default.put(Aes256Cbc.ALGORITHM_NAME, new Aes256Cbc()); - Default.put(AesKw128.AlgorithmName, new AesKw128()); - Default.put(AesKw192.AlgorithmName, new AesKw192()); - Default.put(AesKw256.AlgorithmName, new AesKw256()); + Default.put(AesKw128.ALGORITHM_NAME, new AesKw128()); + Default.put(AesKw192.ALGORITHM_NAME, new AesKw192()); + Default.put(AesKw256.ALGORITHM_NAME, new AesKw256()); - Default.put(Rsa15.AlgorithmName, new Rsa15()); - Default.put(RsaOaep.AlgorithmName, new RsaOaep()); + Default.put(Rsa15.ALGORITHM_NAME, new Rsa15()); + Default.put(RsaOaep.ALGORITHM_NAME, new RsaOaep()); - Default.put( Rs256.AlgorithmName, new Rs256() ); - // Default.put( RsNull.AlgorithmName, new RsNull() ); + Default.put( Rs256.ALGORITHM_NAME, new Rs256() ); + // Default.put( RsNull.ALGORITHM_NAME, new RsNull() ); } private final ConcurrentMap _algorithms = new ConcurrentHashMap(); diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java index c76b4c507de6a..2c8af1810d836 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java @@ -6,26 +6,9 @@ package com.microsoft.azure.keyvault.cryptography; -public final class ByteExtensions { - - public static boolean sequenceEqualConstantTime( byte[] self, byte[] other ) - { - if ( self == null ) - throw new IllegalArgumentException( "self" ); +import java.util.Arrays; - 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; - } +public final class ByteExtensions { public static byte[] or( byte[] self, byte[] other ) { @@ -54,19 +37,10 @@ public static byte[] or( byte[] self, byte[] other, int offset ) } public static byte[] xor( byte[] self, byte[] other ) { - return xor( self, other, 0, false ); - } - - public static byte[] xor( byte[] self, byte[] other, boolean inPlace ) - { - return xor( self, other, 0, inPlace ); - } - - public static byte[] xor( byte[] self, byte[] other, int offset ) { - return xor( self, other, 0, false ); + return xor( self, other, 0 ); } - public static byte[] xor( byte[] self, byte[] other, int offset, boolean inPlace ) + static byte[] xor( byte[] self, byte[] other, int offset ) { if ( self == null ) throw new IllegalArgumentException( "self" ); @@ -77,71 +51,20 @@ public static byte[] xor( byte[] self, byte[] other, int offset, boolean inPlace if ( self.length > other.length - offset ) throw new IllegalArgumentException( "self and other lengths do not match" ); - if ( inPlace ) - { - for ( int i = 0; i < self.length; i++ ) - { - self[i] = (byte)( self[i] ^ other[offset + i] ); - } + byte[] result = new byte[self.length]; - return self; - } - else + for ( int i = 0; i < self.length; i++ ) { - byte[] result = new byte[self.length]; - - for ( int i = 0; i < self.length; i++ ) - { - result[i] = (byte)( self[i] ^ other[offset + i] ); - } - - return result; + result[i] = (byte)( self[i] ^ other[offset + i] ); } - } - - public static byte[] take( byte[] self, int count ) - { - return ByteExtensions.take( self, 0, count ); - } - - - /** - * Takes the first count bytes from the source and - * returns a new array containing those bytes. - * - * @param self The source of the bytes. - * @param offset The starting offset. - * @param count The number of bytes to take. - * @return count bytes from the source as a new array. - */ - public static byte[] take( byte[] self, int offset, int count ) - { - if ( self == null ) - throw new IllegalArgumentException( "self" ); - - if ( offset < 0 ) - throw new IllegalArgumentException( "offset cannot be < 0" ); - - if ( count <= 0 ) - throw new IllegalArgumentException( "count cannot be <= 0" ); - - if ( offset + count > self.length ) - throw new IllegalArgumentException( "offset + count cannot be > self.Length" ); - - byte[] result = new byte[count]; - - System.arraycopy( self, offset, result, 0, count ); return result; } public static void zero( byte[] self ) { - if ( self == null ) - throw new IllegalArgumentException( "self" ); - - for ( int i = 0; i < self.length; i++ ) { - self[i] = 0; + if ( self != null ) { + Arrays.fill(self, (byte)0); } } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java index 4abfcfd8855a6..c8807fc29c49f 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java @@ -84,17 +84,17 @@ public RsaKey(String kid, KeyPair keyPair, Provider provider) { @Override public String getDefaultEncryptionAlgorithm() { - return RsaOaep.AlgorithmName; + return RsaOaep.ALGORITHM_NAME; } @Override public String getDefaultKeyWrapAlgorithm() { - return RsaOaep.AlgorithmName; + return RsaOaep.ALGORITHM_NAME; } @Override public String getDefaultSignatureAlgorithm() { - return Rs256.AlgorithmName; + return Rs256.ALGORITHM_NAME; } @Override @@ -253,7 +253,7 @@ public ListenableFuture> signAsync(final byte[] digest, fin ISignatureTransform signer = algo.createSignatureTransform(_keyPair); try { - return Futures.immediateFuture(Pair.of(signer.sign(digest), Rs256.AlgorithmName)); + return Futures.immediateFuture(Pair.of(signer.sign(digest), Rs256.ALGORITHM_NAME)); } catch (Exception e) { return Futures.immediateFailedFuture(e); } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java index 14e0797b46587..a5e333f092f3b 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java @@ -66,19 +66,19 @@ public String getDefaultEncryptionAlgorithm() { switch (_key.length) { case KeySize128: - return Aes128Cbc.AlgorithmName; + return Aes128Cbc.ALGORITHM_NAME; case KeySize192: - return Aes192Cbc.AlgorithmName; + return Aes192Cbc.ALGORITHM_NAME; case KeySize256: - return Aes128CbcHmacSha256.AlgorithmName; + return Aes128CbcHmacSha256.ALGORITHM_NAME; case KeySize384: - return Aes192CbcHmacSha384.AlgorithmName; + return Aes192CbcHmacSha384.ALGORITHM_NAME; case KeySize512: - return Aes256CbcHmacSha512.AlgorithmName; + return Aes256CbcHmacSha512.ALGORITHM_NAME; } return null; @@ -89,21 +89,21 @@ public String getDefaultKeyWrapAlgorithm() { switch (_key.length) { case KeySize128: - return AesKw128.AlgorithmName; + return AesKw128.ALGORITHM_NAME; case KeySize192: - return AesKw192.AlgorithmName; + return AesKw192.ALGORITHM_NAME; case KeySize256: - return AesKw256.AlgorithmName; + return AesKw256.ALGORITHM_NAME; case KeySize384: // Default to longest allowed key length for wrap - return AesKw256.AlgorithmName; + return AesKw256.ALGORITHM_NAME; case KeySize512: // Default to longest allowed key length for wrap - return AesKw256.AlgorithmName; + return AesKw256.ALGORITHM_NAME; } return null; diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java index 14cf40023b7c8..89a10584294dd 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java @@ -6,63 +6,12 @@ package com.microsoft.azure.keyvault.cryptography.algorithms; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -import javax.crypto.NoSuchPaddingException; - -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; -import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; - public class Aes128Cbc extends AesCbc { - public static final String AlgorithmName = "A128CBC"; - - static final int KeySizeInBytes = 128 >> 3; + private static final int KEY_SIZE = 128; + public static final String ALGORITHM_NAME = "A128CBC"; public Aes128Cbc() { - super(AlgorithmName); - } - - @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); - } - - @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); - } - - @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); - } - - @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + super(ALGORITHM_NAME, KEY_SIZE); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java index 9e75131a3de84..f473aee20d11b 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java @@ -8,9 +8,9 @@ public class Aes128CbcHmacSha256 extends AesCbcHmacSha2 { - public static final String AlgorithmName = "A128CBC-HS256"; + public static final String ALGORITHM_NAME = "A128CBC-HS256"; public Aes128CbcHmacSha256() { - super(AlgorithmName); + super(ALGORITHM_NAME); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java index 4ec8451b47901..fe6f3ff8f1f16 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java @@ -6,64 +6,12 @@ package com.microsoft.azure.keyvault.cryptography.algorithms; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -import javax.crypto.NoSuchPaddingException; - -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; -import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; - public class Aes192Cbc extends AesCbc { - public static final String AlgorithmName = "A192CBC"; - - static final int KeySizeInBytes = 192 >> 3; + private static final int KEY_SIZE = 192; + public static final String ALGORITHM_NAME = "A192CBC"; public Aes192Cbc() { - super(AlgorithmName); - } - - @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); - } - - @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + super(ALGORITHM_NAME, KEY_SIZE); } - - @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); - } - - @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); - } - } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java index 74f279eff8c72..ecfc65f49ff69 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java @@ -8,9 +8,9 @@ public class Aes192CbcHmacSha384 extends AesCbcHmacSha2 { - public static final String AlgorithmName = "A192CBC-HS384"; + public static final String ALGORITHM_NAME = "A192CBC-HS384"; public Aes192CbcHmacSha384() { - super(AlgorithmName); + super(ALGORITHM_NAME); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java index 629b647ec6b92..f198b9012b54c 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java @@ -6,64 +6,12 @@ package com.microsoft.azure.keyvault.cryptography.algorithms; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -import javax.crypto.NoSuchPaddingException; - -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; -import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; - public class Aes256Cbc extends AesCbc { - public static final String AlgorithmName = "A256CBC"; - - static final int KeySizeInBytes = 256 >> 3; + private static final int KEY_SIZE = 256; + public static final String ALGORITHM_NAME = "A256CBC"; public Aes256Cbc() { - super(AlgorithmName); - } - - @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); - } - - @Override - public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + super(ALGORITHM_NAME, KEY_SIZE); } - - @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, null); - } - - @Override - public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - if (key == null || key.length < KeySizeInBytes) { - throw new InvalidKeyException("key must be at least 128 bits in length"); - } - - return new AesCbcDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); - } - } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java index e038c808fec53..61c1aead84b77 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java @@ -8,9 +8,9 @@ public class Aes256CbcHmacSha512 extends AesCbcHmacSha2 { - public static final String AlgorithmName = "A256CBC-HS512"; + public static final String ALGORITHM_NAME = "A256CBC-HS512"; public Aes256CbcHmacSha512() { - super(AlgorithmName); + super(ALGORITHM_NAME); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java index 49edaa57a71b5..d2f891cc13094 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java @@ -10,6 +10,7 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; @@ -23,6 +24,8 @@ public abstract class AesCbc extends SymmetricEncryptionAlgorithm { + final int keySizeInBytes; + final int keySize; static class AesCbcDecryptor implements ICryptoTransform { private final Cipher _cipher; @@ -67,31 +70,49 @@ public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPad } } - protected AesCbc(String name) { + protected AesCbc(String name, int size) { super(name); + keySize = size; + keySizeInBytes = size >> 3; } @Override public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - - return new AesCbcEncryptor(key, iv, null); + + 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, null); } @Override public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - return new AesCbcEncryptor(key, iv, provider); + 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[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - return new AesCbcDecryptor(key, iv, null); + 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, null); } @Override public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { - return new AesCbcDecryptor(key, iv, provider); + 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/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java index c2ccc2a88ab13..0372401e5a039 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java @@ -212,7 +212,7 @@ private static Triple GetAlgorithmParameters(String algorit byte[] hmac_key; Mac hmac; - if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.AlgorithmName)) { + 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)); } @@ -227,7 +227,7 @@ private static Triple GetAlgorithmParameters(String algorit hmac = Mac.getInstance("HmacSHA256"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); - } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.AlgorithmName)) { + } 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)); @@ -242,7 +242,7 @@ private static Triple GetAlgorithmParameters(String algorit hmac = Mac.getInstance("HmacSHA384"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384")); - } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.AlgorithmName)) { + } 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)); diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java index 3c628688ef236..d5696f5998f3f 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java @@ -10,20 +10,20 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.util.Arrays; import javax.crypto.NoSuchPaddingException; -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public final class AesKw128 extends AesKw { - public static final String AlgorithmName = "A128KW"; + public static final String ALGORITHM_NAME = "A128KW"; static final int KeySizeInBytes = 128 >> 3; public AesKw128() { - super(AlgorithmName); + super(ALGORITHM_NAME); } @Override @@ -37,7 +37,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 128 bits long"); } - return super.CreateEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + return super.CreateEncryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); } @Override @@ -51,7 +51,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 128 bits long"); } - return super.CreateDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + return super.CreateDecryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java index dd24b0011a0c1..43225d8e080dd 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java @@ -10,20 +10,20 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.util.Arrays; import javax.crypto.NoSuchPaddingException; -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public final class AesKw192 extends AesKw { - public static final String AlgorithmName = "A192KW"; + public static final String ALGORITHM_NAME = "A192KW"; static final int KeySizeInBytes = 192 >> 3; public AesKw192() { - super(AlgorithmName); + super(ALGORITHM_NAME); } @Override @@ -37,7 +37,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 192 bits long"); } - return super.CreateEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + return super.CreateEncryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); } @Override @@ -51,7 +51,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 192 bits long"); } - return super.CreateDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + return super.CreateDecryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java index 79398e292adc4..b2b514713c96f 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java @@ -10,20 +10,20 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.util.Arrays; import javax.crypto.NoSuchPaddingException; -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; public final class AesKw256 extends AesKw { - public static final String AlgorithmName = "A256KW"; + public static final String ALGORITHM_NAME = "A256KW"; static final int KeySizeInBytes = 256 >> 3; public AesKw256() { - super(AlgorithmName); + super(ALGORITHM_NAME); } @Override @@ -37,7 +37,7 @@ public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 256 bits long"); } - return super.CreateEncryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + return super.CreateEncryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); } @Override @@ -51,7 +51,7 @@ public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider throw new IllegalArgumentException("key must be at least 256 bits long"); } - return super.CreateDecryptor(ByteExtensions.take(key, KeySizeInBytes), iv, provider); + return super.CreateDecryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java index 54a4fd4572361..eddafecac6b28 100644 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java @@ -12,7 +12,6 @@ import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ISignatureTransform; /** @@ -75,15 +74,15 @@ public boolean verify(byte[] digest, byte[] signature) throws NoSuchAlgorithmExc byte[] EM2 = EMSA_PKCS1_V1_5_ENCODE_HASH(digest, _emLen, "SHA-256"); // Use constant time compare - return ByteExtensions.sequenceEqualConstantTime(EM, EM2); + return sequenceEqualConstantTime(EM, EM2); } } - public final static String AlgorithmName = "RS256"; + public final static String ALGORITHM_NAME = "RS256"; public Rs256() { - super(AlgorithmName); + super(ALGORITHM_NAME); } @Override @@ -91,4 +90,23 @@ public ISignatureTransform createSignatureTransform(KeyPair keyPair) { return new Rs256SignatureTransform(keyPair); } + + private 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; + } } diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java index 4770183bb3ab8..18ea8d28514fd 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java @@ -72,10 +72,10 @@ public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPad final static String RSA15 = "RSA/ECB/PKCS1Padding"; - public final static String AlgorithmName = "RSA1_5"; + public final static String ALGORITHM_NAME = "RSA1_5"; public Rsa15() { - super(AlgorithmName); + super(ALGORITHM_NAME); } @Override diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java index 55b57b6acd633..38c3e4131231b 100755 --- a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java @@ -72,10 +72,10 @@ public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPad final static String RSAOAEP = "RSA/ECB/OAEPWithSHA1AndMGF1Padding"; - public final static String AlgorithmName = "RSA-OAEP"; + public final static String ALGORITHM_NAME = "RSA-OAEP"; public RsaOaep() { - super(AlgorithmName); + super(ALGORITHM_NAME); } @Override diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java index 351f22a1ce993..b9bbf4a65e1e9 100644 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.fail; import java.security.Provider; +import java.util.Arrays; import org.junit.After; import org.junit.AfterClass; @@ -11,7 +12,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import com.microsoft.azure.keyvault.cryptography.ByteExtensions; import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; @@ -63,7 +63,7 @@ public void testAes128CbcOneBlock() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(encrypted, 16), ED); + assertArrayEquals(Arrays.copyOfRange(encrypted, 0, 16), ED); } catch (Exception e) { fail(e.getMessage()); } @@ -81,7 +81,7 @@ public void testAes128CbcOneBlock() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(decrypted, 16), PLAIN); + assertArrayEquals(Arrays.copyOfRange(decrypted, 0, 16), PLAIN); } catch (Exception e) { fail(e.getMessage()); } @@ -110,7 +110,7 @@ public void testAes128CbcTwoBlock() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(encrypted, 32), ED); + assertArrayEquals(Arrays.copyOfRange(encrypted, 0, 32), ED); } catch (Exception e) { fail(e.getMessage()); } @@ -128,7 +128,7 @@ public void testAes128CbcTwoBlock() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(decrypted, 32), PLAIN); + assertArrayEquals(Arrays.copyOfRange(decrypted, 0, 32), PLAIN); } catch (Exception e) { fail(e.getMessage()); } @@ -157,7 +157,7 @@ public void testAes128CbcOneBlock_ExcessKeyMaterial() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(encrypted, 16),ED); + assertArrayEquals(Arrays.copyOfRange(encrypted, 0, 16),ED); } catch (Exception e) { fail(e.getMessage()); } @@ -175,7 +175,7 @@ public void testAes128CbcOneBlock_ExcessKeyMaterial() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(decrypted, 16), PLAIN); + assertArrayEquals(Arrays.copyOfRange(decrypted, 0, 16), PLAIN); } catch (Exception e) { fail(e.getMessage()); } @@ -204,7 +204,7 @@ public void testAes128CbcTwoBlock_ExcessKeyMaterial() { encrypted = encryptor.doFinal(PLAIN); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(encrypted, 32), ED); + assertArrayEquals(Arrays.copyOfRange(encrypted, 0, 32), ED); } catch (Exception e) { fail(e.getMessage()); } @@ -222,7 +222,7 @@ public void testAes128CbcTwoBlock_ExcessKeyMaterial() { decrypted = decryptor.doFinal(encrypted); // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding - assertArrayEquals(ByteExtensions.take(decrypted, 32), PLAIN); + assertArrayEquals(Arrays.copyOfRange(decrypted, 0, 32), PLAIN); } catch (Exception e) { fail(e.getMessage()); } diff --git a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java index 18cf7db616e18..799827bd349c5 100755 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -57,19 +57,19 @@ public void testRsa15() throws Exception { RsaKey key = getTestRsaKey(); // Wrap and Unwrap - Pair wrapped = key.wrapKeyAsync(CEK, Rsa15.AlgorithmName).get(); + Pair wrapped = key.wrapKeyAsync(CEK, Rsa15.ALGORITHM_NAME).get(); byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); // Assert - assertEquals(Rsa15.AlgorithmName, wrapped.getRight()); + assertEquals(Rsa15.ALGORITHM_NAME, wrapped.getRight()); assertArrayEquals(CEK, unwrapped); // Encrypt and Decrypt - Triple encrypted = key.encryptAsync(CEK, null, null, Rsa15.AlgorithmName).get(); + Triple encrypted = key.encryptAsync(CEK, null, null, Rsa15.ALGORITHM_NAME).get(); byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get(); // Assert - assertEquals(Rsa15.AlgorithmName, encrypted.getRight()); + assertEquals(Rsa15.ALGORITHM_NAME, encrypted.getRight()); assertArrayEquals(CEK, decrypted); key.close(); @@ -81,19 +81,19 @@ public void testRsaOaep() throws Exception { RsaKey key = getTestRsaKey(); // Wrap and Unwrap - Pair wrapped = key.wrapKeyAsync(CEK, RsaOaep.AlgorithmName).get(); + Pair wrapped = key.wrapKeyAsync(CEK, RsaOaep.ALGORITHM_NAME).get(); byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); // Assert - assertEquals(RsaOaep.AlgorithmName, wrapped.getRight()); + assertEquals(RsaOaep.ALGORITHM_NAME, wrapped.getRight()); assertArrayEquals(CEK, unwrapped); // Encrypt and Decrypt - Triple encrypted = key.encryptAsync(CEK, null, null, RsaOaep.AlgorithmName).get(); + Triple encrypted = key.encryptAsync(CEK, null, null, RsaOaep.ALGORITHM_NAME).get(); byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get(); // Assert - assertEquals(RsaOaep.AlgorithmName, encrypted.getRight()); + assertEquals(RsaOaep.ALGORITHM_NAME, encrypted.getRight()); assertArrayEquals(CEK, decrypted); key.close(); @@ -104,16 +104,16 @@ public void testDefaultAlgorithm() throws Exception { RsaKey key = getTestRsaKey(); - assertEquals(RsaOaep.AlgorithmName, key.getDefaultEncryptionAlgorithm()); - assertEquals(RsaOaep.AlgorithmName, key.getDefaultKeyWrapAlgorithm()); - assertEquals(Rs256.AlgorithmName, key.getDefaultSignatureAlgorithm()); + assertEquals(RsaOaep.ALGORITHM_NAME, key.getDefaultEncryptionAlgorithm()); + assertEquals(RsaOaep.ALGORITHM_NAME, key.getDefaultKeyWrapAlgorithm()); + assertEquals(Rs256.ALGORITHM_NAME, key.getDefaultSignatureAlgorithm()); // Wrap and Unwrap Pair wrapped = key.wrapKeyAsync(CEK, key.getDefaultKeyWrapAlgorithm()).get(); byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); // Assert - assertEquals(RsaOaep.AlgorithmName, wrapped.getRight()); + assertEquals(RsaOaep.ALGORITHM_NAME, wrapped.getRight()); assertArrayEquals(CEK, unwrapped); // Encrypt and Decrypt @@ -121,7 +121,7 @@ public void testDefaultAlgorithm() throws Exception { byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get(); // Assert - assertEquals(RsaOaep.AlgorithmName, encrypted.getRight()); + assertEquals(RsaOaep.ALGORITHM_NAME, encrypted.getRight()); assertArrayEquals(CEK, decrypted); key.close(); From c89a1aff9a46d2206ef7f186365a1ccb93190b3a Mon Sep 17 00:00:00 2001 From: Pooneh Date: Tue, 13 Sep 2016 22:34:23 -0700 Subject: [PATCH 14/14] Removing the ServiceResponse<> off return type and remove with*() for readonly objects. --- .../KeyVaultKeyResolverBCProviderTest.java | 10 +- ...eyVaultKeyResolverDefaultProviderTest.java | 8 +- .../azure/keyvault/KeyVaultClient.java | 258 +- .../azure/keyvault/KeyVaultClientImpl.java | 2066 +++++++++++++---- .../azure/keyvault/models/KeyBundle.java | 11 - .../azure/keyvault/models/KeyItem.java | 11 - .../azure/keyvault/models/SecretBundle.java | 22 - .../azure/keyvault/models/SecretItem.java | 11 - .../test/CertificateOperationsTest.java | 86 +- .../keyvault/test/KeyOperationsTest.java | 70 +- .../keyvault/test/SecretOperationsTest.java | 30 +- 11 files changed, 1864 insertions(+), 719 deletions(-) diff --git a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java index f7f16bb09ca29..813b4c3ee5ad6 100755 --- a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java @@ -39,7 +39,6 @@ import com.microsoft.azure.keyvault.requests.CreateKeyRequest; import com.microsoft.azure.keyvault.requests.SetSecretRequest; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; -import com.microsoft.rest.ServiceResponse; public class KeyVaultKeyResolverBCProviderTest extends KeyVaultClientIntegrationTestBase { @@ -81,8 +80,7 @@ public void KeyVault_KeyVaultKeyResolver_Key() throws InterruptedException, Exec try { // Create a key on a vault. CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); - ServiceResponse response = keyVaultClient.createKey(request); - KeyBundle bundle = response != null ? response.getBody() : null; + KeyBundle bundle = keyVaultClient.createKey(request); if ( bundle != null ) { @@ -126,7 +124,7 @@ public void KeyVault_KeyVaultKeyResolver_Secret128Base64() throws InterruptedExc try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); - SecretBundle secretBundle = keyVaultClient.setSecret( request ).getBody(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); if ( secretBundle != null ) { @@ -186,7 +184,7 @@ public void KeyVault_KeyVaultKeyResolver_Secret192Base64() throws InterruptedExc try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); - SecretBundle secretBundle = keyVaultClient.setSecret( request ).getBody(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); if ( secretBundle != null ) { @@ -246,7 +244,7 @@ public void KeyVault_KeyVaultKeyResolver_Secret256Base64() throws InterruptedExc try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); - SecretBundle secretBundle = keyVaultClient.setSecret( request ).getBody(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); if ( secretBundle != null ) { diff --git a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java index 63708e2b6a085..62777c9b26103 100755 --- a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java @@ -81,7 +81,7 @@ public void KeyVault_KeyVaultKeyResolver_Key() throws InterruptedException, Exec try { // Create a key on a vault. CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); - KeyBundle keyBundle = keyVaultClient.createKey(request).getBody(); + KeyBundle keyBundle = keyVaultClient.createKey(request); try { @@ -116,7 +116,7 @@ public void KeyVault_KeyVaultKeyResolver_Secret128Base64() throws InterruptedExc try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); - SecretBundle secretBundle = keyVaultClient.setSecret(request).getBody(); + SecretBundle secretBundle = keyVaultClient.setSecret(request); if ( secretBundle != null ) { @@ -176,7 +176,7 @@ public void KeyVault_KeyVaultKeyResolver_Secret192Base64() throws InterruptedExc try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); - SecretBundle secretBundle = keyVaultClient.setSecret( request ).getBody(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); if ( secretBundle != null ) { @@ -249,7 +249,7 @@ public void KeyVault_KeyVaultKeyResolver_Secret256Base64() throws InterruptedExc try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); - SecretBundle secretBundle = keyVaultClient.setSecret( request ).getBody(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); if ( secretBundle != null ) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java index 95a998e02c63b..c49e98428ee1c 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java @@ -192,9 +192,9 @@ interface KeyVaultClientService { * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse createKey(CreateKeyRequest createKeyRequest) + public KeyBundle createKey(CreateKeyRequest createKeyRequest) throws KeyVaultErrorException, IllegalArgumentException, IOException { return innerKeyVaultClient.createKey( createKeyRequest.vaultBaseUrl(), @@ -234,9 +234,9 @@ public ServiceCall createKeyAsync(CreateKeyRequest createKeyRequest, * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse importKey(ImportKeyRequest importKeyRequest) + public KeyBundle importKey(ImportKeyRequest importKeyRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.importKey( importKeyRequest.vaultBaseUrl(), @@ -274,9 +274,9 @@ public ServiceCall importKeyAsync(ImportKeyRequest importKeyRequest, * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse deleteKey(String vaultBaseUrl, String keyName) + public KeyBundle deleteKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.deleteKey(vaultBaseUrl, keyName); } @@ -301,9 +301,9 @@ public ServiceCall deleteKeyAsync(String vaultBaseUrl, String keyName * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse updateKey(UpdateKeyRequest updateKeyRequest) + public KeyBundle updateKey(UpdateKeyRequest updateKeyRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateKey( updateKeyRequest.vaultBaseUrl(), @@ -340,9 +340,9 @@ public ServiceCall updateKeyAsync(UpdateKeyRequest updateKeyRequest, * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse getKey(String keyIdentifier) + public KeyBundle getKey(String keyIdentifier) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.getKey(id.vault, id.name, id.version == null ? "" : id.version); @@ -368,9 +368,9 @@ public ServiceCall getKeyAsync(String keyIdentifier, final ServiceCal * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse getKey(String vaultBaseUrl, String keyName) + public KeyBundle getKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKey(vaultBaseUrl, keyName, ""); } @@ -396,9 +396,9 @@ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, f * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse getKey(String vaultBaseUrl, String keyName, String keyVersion) + public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKey(vaultBaseUrl, keyName, keyVersion); } @@ -424,9 +424,9 @@ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, S * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> if successful. */ - public ServiceResponse> listKeyVersions(final String vaultBaseUrl, final String keyName) + public PagedList listKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName); } @@ -447,13 +447,13 @@ public ServiceCall> listKeyVersionsAsync(final String vaultBaseUrl * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> if successful. */ - public ServiceResponse> listKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) + public PagedList listKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName, maxresults); } @@ -463,7 +463,7 @@ public ServiceResponse> listKeyVersions(final String vaultBas * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -478,9 +478,9 @@ public ServiceCall> listKeyVersionsAsync(final String vaultBaseUrl * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> if successful. */ - public ServiceResponse> listKeys(final String vaultBaseUrl) + public PagedList listKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeys(vaultBaseUrl); } @@ -499,13 +499,13 @@ public ServiceCall> listKeysAsync(final String vaultBaseUrl, final * List keys in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> if successful. */ - public ServiceResponse> listKeys(final String vaultBaseUrl, final Integer maxresults) + public PagedList listKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeys(vaultBaseUrl, maxresults); } @@ -514,7 +514,7 @@ public ServiceResponse> listKeys(final String vaultBaseUrl, f * List keys in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -530,9 +530,9 @@ public ServiceCall> listKeysAsync(final String vaultBaseUrl, final * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the BackupKeyResult object wrapped in {@link ServiceResponse} if successful. + * @return the BackupKeyResult if successful. */ - public ServiceResponse backupKey(String vaultBaseUrl, String keyName) + public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.backupKey(vaultBaseUrl, keyName); } @@ -557,9 +557,9 @@ public ServiceCall backupKeyAsync(String vaultBaseUrl, String k * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle if successful. */ - public ServiceResponse restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) + public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.restoreKey(vaultBaseUrl, keyBundleBackup); } @@ -585,9 +585,9 @@ public ServiceCall restoreKeyAsync(String vaultBaseUrl, byte[] keyBun * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult if successful. */ - public ServiceResponse encrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) + public KeyOperationResult encrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.encrypt(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -616,9 +616,9 @@ public ServiceCall encryptAsync(String keyIdentifier, JsonWe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult if successful. */ - public ServiceResponse decrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) + public KeyOperationResult decrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.decrypt(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -647,9 +647,9 @@ public ServiceCall decryptAsync(String keyIdentifier, JsonWe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult if successful. */ - public ServiceResponse sign(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value) + public KeyOperationResult sign(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.sign(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -679,9 +679,9 @@ public ServiceCall signAsync(String keyIdentifier, JsonWebKe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyVerifyResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyVerifyResult if successful. */ - public ServiceResponse verify(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) + public KeyVerifyResult verify(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.verify(id.vault, id.name, id.version == null ? "" : id.version, algorithm, digest, signature); @@ -711,9 +711,9 @@ public ServiceCall verifyAsync(String keyIdentifier, JsonWebKey * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult if successful. */ - public ServiceResponse wrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) + public KeyOperationResult wrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.wrapKey(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -742,9 +742,9 @@ public ServiceCall wrapKeyAsync(String keyIdentifier, JsonWe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult if successful. */ - public ServiceResponse unwrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) + public KeyOperationResult unwrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { KeyIdentifier id = new KeyIdentifier(keyIdentifier); return innerKeyVaultClient.unwrapKey(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); @@ -772,9 +772,9 @@ public ServiceCall unwrapKeyAsync(String keyIdentifier, Json * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle if successful. */ - public ServiceResponse setSecret(SetSecretRequest setSecretRequest) + public SecretBundle setSecret(SetSecretRequest setSecretRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.setSecret( setSecretRequest.vaultBaseUrl(), @@ -812,9 +812,9 @@ public ServiceCall setSecretAsync(SetSecretRequest setSecretReques * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle if successful. */ - public ServiceResponse deleteSecret(String vaultBaseUrl, String secretName) + public SecretBundle deleteSecret(String vaultBaseUrl, String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.deleteSecret(vaultBaseUrl, secretName); } @@ -839,9 +839,9 @@ public ServiceCall deleteSecretAsync(String vaultBaseUrl, String s * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle if successful. */ - public ServiceResponse updateSecret(UpdateSecretRequest updateSecretRequest) + public SecretBundle updateSecret(UpdateSecretRequest updateSecretRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateSecret( updateSecretRequest.vaultBaseUrl(), @@ -878,9 +878,9 @@ public ServiceCall updateSecretAsync(UpdateSecretRequest updateSec * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle if successful. */ - public ServiceResponse getSecret(String secretIdentifier) + public SecretBundle getSecret(String secretIdentifier) throws KeyVaultErrorException, IOException, IllegalArgumentException { SecretIdentifier id = new SecretIdentifier(secretIdentifier); return innerKeyVaultClient.getSecret(id.vault, id.name, id.version == null ? "" : id.version); @@ -906,9 +906,9 @@ public ServiceCall getSecretAsync(String secretIdentifier, final S * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle if successful. */ - public ServiceResponse getSecret(String vaultBaseUrl, String secretName) + public SecretBundle getSecret(String vaultBaseUrl, String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecret(vaultBaseUrl, secretName, ""); } @@ -934,9 +934,9 @@ public ServiceCall getSecretAsync(String vaultBaseUrl, String secr * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle if successful. */ - public ServiceResponse getSecret(String vaultBaseUrl, String secretName, String secretVersion) + public SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecret(vaultBaseUrl, secretName, secretVersion == null ? "" : secretVersion); } @@ -961,9 +961,9 @@ public ServiceCall getSecretAsync(String vaultBaseUrl, String secr * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> if successful. */ - public ServiceResponse> listSecrets(final String vaultBaseUrl) + public PagedList listSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecrets(vaultBaseUrl); } @@ -982,13 +982,13 @@ public ServiceCall> listSecretsAsync(final String vaultBaseUrl, * List secrets in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of secrets to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> if successful. */ - public ServiceResponse> listSecrets(final String vaultBaseUrl, final Integer maxresults) + public PagedList listSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecrets(vaultBaseUrl, maxresults); } @@ -997,7 +997,7 @@ public ServiceResponse> listSecrets(final String vaultBase * List secrets in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of secrets to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1013,9 +1013,9 @@ public ServiceCall> listSecretsAsync(final String vaultBaseUrl, * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> if successful. */ - public ServiceResponse> listSecretVersions(final String vaultBaseUrl, final String secretName) + public PagedList listSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName); } @@ -1036,13 +1036,13 @@ public ServiceCall> listSecretVersionsAsync(final String vaultB * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> if successful. */ - public ServiceResponse> listSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) + public PagedList listSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName, maxresults); } @@ -1052,7 +1052,7 @@ public ServiceResponse> listSecretVersions(final String va * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1067,9 +1067,9 @@ public ServiceCall> listSecretVersionsAsync(final String vaultB * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> if successful. */ - public ServiceResponse> listCertificates(final String vaultBaseUrl) + public PagedList listCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificates(vaultBaseUrl); } @@ -1088,13 +1088,13 @@ public ServiceCall> listCertificatesAsync(final String vau * List certificates in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> if successful. */ - public ServiceResponse> listCertificates(final String vaultBaseUrl, final Integer maxresults) + public PagedList listCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificates(vaultBaseUrl, maxresults); } @@ -1103,7 +1103,7 @@ public ServiceResponse> listCertificates(final String * List certificates in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1119,9 +1119,9 @@ public ServiceCall> listCertificatesAsync(final String vau * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse deleteCertificate(String vaultBaseUrl, String certificateName) + public CertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.deleteCertificate(vaultBaseUrl, certificateName); } @@ -1146,9 +1146,9 @@ public ServiceCall deleteCertificateAsync(String vaultBaseUrl * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the Contacts object wrapped in {@link ServiceResponse} if successful. + * @return the Contacts if successful. */ - public ServiceResponse setCertificateContacts(String vaultBaseUrl, Contacts contacts) + public Contacts setCertificateContacts(String vaultBaseUrl, Contacts contacts) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.setCertificateContacts(vaultBaseUrl, contacts); } @@ -1172,9 +1172,9 @@ public ServiceCall setCertificateContactsAsync(String vaultBaseUrl, Co * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the Contacts object wrapped in {@link ServiceResponse} if successful. + * @return the Contacts if successful. */ - public ServiceResponse getCertificateContacts(String vaultBaseUrl) + public Contacts getCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateContacts(vaultBaseUrl); } @@ -1197,9 +1197,9 @@ public ServiceCall getCertificateContactsAsync(String vaultBaseUrl, fi * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the Contacts object wrapped in {@link ServiceResponse} if successful. + * @return the Contacts if successful. */ - public ServiceResponse deleteCertificateContacts(String vaultBaseUrl) + public Contacts deleteCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.deleteCertificateContacts(vaultBaseUrl); } @@ -1222,9 +1222,9 @@ public ServiceCall deleteCertificateContactsAsync(String vaultBaseUrl, * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateIssuerItem> if successful. */ - public ServiceResponse> listCertificateIssuers(final String vaultBaseUrl) + public PagedList listCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl); } @@ -1243,13 +1243,13 @@ public ServiceCall> listCertificateIssuersAsync(fina * List certificate issuers for the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateIssuerItem> if successful. */ - public ServiceResponse> listCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) + public PagedList listCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl, maxresults); } @@ -1258,7 +1258,7 @@ public ServiceResponse> listCertificateIssuers( * List certificate issuers for the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1274,9 +1274,9 @@ public ServiceCall> listCertificateIssuersAsync(fina * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle if successful. */ - public ServiceResponse setCertificateIssuer(SetCertificateIssuerRequest setCertificateIssuerRequest) + public IssuerBundle setCertificateIssuer(SetCertificateIssuerRequest setCertificateIssuerRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.setCertificateIssuer( setCertificateIssuerRequest.vaultBaseUrl(), @@ -1314,9 +1314,9 @@ public ServiceCall setCertificateIssuerAsync(SetCertificateIssuerR * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle if successful. */ - public ServiceResponse updateCertificateIssuer(UpdateCertificateIssuerRequest updateCertificateIssuerRequest) + public IssuerBundle updateCertificateIssuer(UpdateCertificateIssuerRequest updateCertificateIssuerRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateCertificateIssuer( updateCertificateIssuerRequest.vaultBaseUrl(), @@ -1355,9 +1355,9 @@ public ServiceCall updateCertificateIssuerAsync(UpdateCertificateI * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle if successful. */ - public ServiceResponse getCertificateIssuer(String vaultBaseUrl, String issuerName) + public IssuerBundle getCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuer(vaultBaseUrl, issuerName); } @@ -1382,9 +1382,9 @@ public ServiceCall getCertificateIssuerAsync(String vaultBaseUrl, * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle if successful. */ - public ServiceResponse deleteCertificateIssuer(String vaultBaseUrl, String issuerName) + public IssuerBundle deleteCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.deleteCertificateIssuer(vaultBaseUrl, issuerName); } @@ -1409,9 +1409,9 @@ public ServiceCall deleteCertificateIssuerAsync(String vaultBaseUr * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateOperation if successful. */ - public ServiceResponse createCertificate(CreateCertificateRequest createCertificateRequest) + public CertificateOperation createCertificate(CreateCertificateRequest createCertificateRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.createCertificate( createCertificateRequest.vaultBaseUrl(), @@ -1447,9 +1447,9 @@ public ServiceCall createCertificateAsync(CreateCertificat * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse importCertificate(ImportCertificateRequest importCertificateRequest) + public CertificateBundle importCertificate(ImportCertificateRequest importCertificateRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.importCertificate( importCertificateRequest.vaultBaseUrl(), @@ -1489,9 +1489,9 @@ public ServiceCall importCertificateAsync(ImportCertificateRe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> if successful. */ - public ServiceResponse> listCertificateVersions(final String vaultBaseUrl, final String certificateName) + public PagedList listCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName); } @@ -1512,13 +1512,13 @@ public ServiceCall> listCertificateVersionsAsync(final Str * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> if successful. */ - public ServiceResponse> listCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) + public PagedList listCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName, maxresults); } @@ -1528,7 +1528,7 @@ public ServiceResponse> listCertificateVersions(final * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1544,9 +1544,9 @@ public ServiceCall> listCertificateVersionsAsync(final Str * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificatePolicy object wrapped in {@link ServiceResponse} if successful. + * @return the CertificatePolicy if successful. */ - public ServiceResponse getCertificatePolicy(String vaultBaseUrl, String certificateName) + public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificatePolicy(vaultBaseUrl, certificateName); } @@ -1571,9 +1571,9 @@ public ServiceCall getCertificatePolicyAsync(String vaultBase * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificatePolicy object wrapped in {@link ServiceResponse} if successful. + * @return the CertificatePolicy if successful. */ - public ServiceResponse updateCertificatePolicy(UpdateCertificatePolicyRequest updateCertificatePolicyRequest) + public CertificatePolicy updateCertificatePolicy(UpdateCertificatePolicyRequest updateCertificatePolicyRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateCertificatePolicy( updateCertificatePolicyRequest.vaultBaseUrl(), @@ -1605,9 +1605,9 @@ public ServiceCall updateCertificatePolicyAsync(UpdateCertifi * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse updateCertificate(UpdateCertificateRequest updateCertificateRequest) + public CertificateBundle updateCertificate(UpdateCertificateRequest updateCertificateRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateCertificate( updateCertificateRequest.vaultBaseUrl(), @@ -1644,9 +1644,9 @@ public ServiceCall updateCertificateAsync(UpdateCertificateRe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse getCertificate(String certificateIdentifier) + public CertificateBundle getCertificate(String certificateIdentifier) throws KeyVaultErrorException, IOException, IllegalArgumentException { CertificateIdentifier id = new CertificateIdentifier(certificateIdentifier); return innerKeyVaultClient.getCertificate(id.vault, id.name, id.version == null ? "" : id.version); @@ -1672,9 +1672,9 @@ public ServiceCall getCertificateAsync(String certificateIden * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse getCertificate(String vaultBaseUrl, String certificateName) + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificate(vaultBaseUrl, certificateName, ""); } @@ -1700,9 +1700,9 @@ public ServiceCall getCertificateAsync(String vaultBaseUrl, S * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificate(vaultBaseUrl, certificateName, certificateVersion); } @@ -1728,9 +1728,9 @@ public ServiceCall getCertificateAsync(String vaultBaseUrl, S * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateOperation if successful. */ - public ServiceResponse updateCertificateOperation(UpdateCertificateOperationRequest updateCertificateOperationRequest) + public CertificateOperation updateCertificateOperation(UpdateCertificateOperationRequest updateCertificateOperationRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.updateCertificateOperation( updateCertificateOperationRequest.vaultBaseUrl(), @@ -1762,9 +1762,9 @@ public ServiceCall updateCertificateOperationAsync(UpdateC * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateOperation if successful. */ - public ServiceResponse getCertificateOperation(String vaultBaseUrl, String certificateName) + public CertificateOperation getCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateOperation(vaultBaseUrl, certificateName); } @@ -1789,9 +1789,9 @@ public ServiceCall getCertificateOperationAsync(String vau * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateOperation if successful. */ - public ServiceResponse deleteCertificateOperation(String vaultBaseUrl, String certificateName) + public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.deleteCertificateOperation(vaultBaseUrl, certificateName); } @@ -1816,9 +1816,9 @@ public ServiceCall deleteCertificateOperationAsync(String * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle if successful. */ - public ServiceResponse mergeCertificate(MergeCertificateRequest mergeCertificateRequest) + public CertificateBundle mergeCertificate(MergeCertificateRequest mergeCertificateRequest) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.mergeCertificate( mergeCertificateRequest.vaultBaseUrl(), @@ -1855,11 +1855,11 @@ public ServiceCall mergeCertificateAsync(MergeCertificateRequ * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the String object wrapped in {@link ServiceResponse} if successful. + * @return the String if successful. */ - public ServiceResponse getPendingCertificateSigningRequest(String vaultBaseUrl, String certificateName) + public String getPendingCertificateSigningRequest(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getPendingCertificateSigningRequestAsync(vaultBaseUrl, certificateName).toBlocking().single(); + return getPendingCertificateSigningRequestWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -1871,7 +1871,7 @@ public ServiceResponse getPendingCertificateSigningRequest(String vaultB * @return the {@link ServiceCall} object */ public ServiceCall getPendingCertificateSigningRequestAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - return ServiceCall.create(getPendingCertificateSigningRequestAsync(vaultBaseUrl, certificateName), serviceCallback); + return ServiceCall.create(getPendingCertificateSigningRequestWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); } /** @@ -1881,7 +1881,7 @@ public ServiceCall getPendingCertificateSigningRequestAsync(String vault * @param certificateName The name of the certificate * @return the observable to the String object */ - private Observable> getPendingCertificateSigningRequestAsync(String vaultBaseUrl, String certificateName) { + private Observable> getPendingCertificateSigningRequestWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java index ddeb203106bf6..bfafedeedfcc8 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java @@ -455,10 +455,10 @@ interface KeyVaultClientService { * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return createKeyAsync(vaultBaseUrl, keyName, kty).toBlocking().single(); + public KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty).toBlocking().single().getBody(); } /** @@ -471,7 +471,7 @@ public ServiceResponse createKey(String vaultBaseUrl, String keyName, * @return the {@link ServiceCall} object */ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, final ServiceCallback serviceCallback) { - return ServiceCall.create(createKeyAsync(vaultBaseUrl, keyName, kty), serviceCallback); + return ServiceCall.create(createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty), serviceCallback); } /** @@ -482,7 +482,24 @@ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' * @return the observable to the KeyBundle object */ - public Observable> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { + public Observable createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Creates a new, named, key in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @return the observable to the KeyBundle object + */ + public Observable> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -533,10 +550,10 @@ public Observable> call(Response respon * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return createKeyAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags).toBlocking().single(); + public KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags).toBlocking().single().getBody(); } /** @@ -553,7 +570,7 @@ public ServiceResponse createKey(String vaultBaseUrl, String keyName, * @return the {@link ServiceCall} object */ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(createKeyAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags), serviceCallback); + return ServiceCall.create(createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags), serviceCallback); } /** @@ -568,7 +585,28 @@ public ServiceCall createKeyAsync(String vaultBaseUrl, String keyName * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the KeyBundle object */ - public Observable> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) { + public Observable createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Creates a new, named, key in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param kty The type of key to create. Valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param keySize The key size in bytes. e.g. 1024 or 2048. + * @param keyOps the List<JsonWebKeyOperation> value + * @param keyAttributes the KeyAttributes value + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the KeyBundle object + */ + public Observable> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -621,10 +659,10 @@ private ServiceResponse createKeyDelegate(Response resp * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse importKey(String vaultBaseUrl, String keyName, JsonWebKey key) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return importKeyAsync(vaultBaseUrl, keyName, key).toBlocking().single(); + public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key).toBlocking().single().getBody(); } /** @@ -637,7 +675,7 @@ public ServiceResponse importKey(String vaultBaseUrl, String keyName, * @return the {@link ServiceCall} object */ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, final ServiceCallback serviceCallback) { - return ServiceCall.create(importKeyAsync(vaultBaseUrl, keyName, key), serviceCallback); + return ServiceCall.create(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key), serviceCallback); } /** @@ -648,7 +686,24 @@ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName * @param key The Json web key * @return the observable to the KeyBundle object */ - public Observable> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key) { + public Observable importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key) { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Imports a key into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param key The Json web key + * @return the observable to the KeyBundle object + */ + public Observable> importKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKey key) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -697,10 +752,10 @@ public Observable> call(Response respon * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse importKey(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return importKeyAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags).toBlocking().single(); + public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags).toBlocking().single().getBody(); } /** @@ -716,7 +771,7 @@ public ServiceResponse importKey(String vaultBaseUrl, String keyName, * @return the {@link ServiceCall} object */ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(importKeyAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags), serviceCallback); + return ServiceCall.create(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags), serviceCallback); } /** @@ -730,7 +785,27 @@ public ServiceCall importKeyAsync(String vaultBaseUrl, String keyName * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the KeyBundle object */ - public Observable> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) { + public Observable importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Imports a key into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @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 + * @return the observable to the KeyBundle object + */ + public Observable> importKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -780,10 +855,10 @@ private ServiceResponse importKeyDelegate(Response resp * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse deleteKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return deleteKeyAsync(vaultBaseUrl, keyName).toBlocking().single(); + public KeyBundle deleteKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().getBody(); } /** @@ -795,7 +870,23 @@ public ServiceResponse deleteKey(String vaultBaseUrl, String keyName) * @return the {@link ServiceCall} object */ public ServiceCall deleteKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { - return ServiceCall.create(deleteKeyAsync(vaultBaseUrl, keyName), serviceCallback); + return ServiceCall.create(deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName), serviceCallback); + } + + /** + * Deletes the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the observable to the KeyBundle object + */ + public Observable deleteKeyAsync(String vaultBaseUrl, String keyName) { + return deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -805,7 +896,7 @@ public ServiceCall deleteKeyAsync(String vaultBaseUrl, String keyName * @param keyName The name of the key * @return the observable to the KeyBundle object */ - public Observable> deleteKeyAsync(String vaultBaseUrl, String keyName) { + public Observable> deleteKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -846,10 +937,10 @@ private ServiceResponse deleteKeyDelegate(Response resp * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse updateKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateKeyAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single(); + public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single().getBody(); } /** @@ -862,7 +953,7 @@ public ServiceResponse updateKey(String vaultBaseUrl, String keyName, * @return the {@link ServiceCall} object */ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateKeyAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + return ServiceCall.create(updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); } /** @@ -873,7 +964,24 @@ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName * @param keyVersion The version of the key * @return the observable to the KeyBundle object */ - public Observable> updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { + public Observable updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates the Key Attributes associated with the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @return the observable to the KeyBundle object + */ + public Observable> updateKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -920,10 +1028,10 @@ public Observable> call(Response respon * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateKeyAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).toBlocking().single(); + public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).toBlocking().single().getBody(); } /** @@ -939,7 +1047,27 @@ public ServiceResponse updateKey(String vaultBaseUrl, String keyName, * @return the {@link ServiceCall} object */ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateKeyAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags), serviceCallback); + return ServiceCall.create(updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags), serviceCallback); + } + + /** + * Updates the Key Attributes associated with the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. + * @param keyAttributes the KeyAttributes value + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the KeyBundle object + */ + public Observable updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -953,7 +1081,7 @@ public ServiceCall updateKeyAsync(String vaultBaseUrl, String keyName * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the KeyBundle object */ - public Observable> updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) { + public Observable> updateKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1004,10 +1132,10 @@ private ServiceResponse updateKeyDelegate(Response resp * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyBundle object wrapped in {@link ServiceResponse} if successful. + * @return the KeyBundle object if successful. */ - public ServiceResponse getKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getKeyAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single(); + public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single().getBody(); } /** @@ -1020,7 +1148,24 @@ public ServiceResponse getKey(String vaultBaseUrl, String keyName, St * @return the {@link ServiceCall} object */ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { - return ServiceCall.create(getKeyAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + return ServiceCall.create(getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + } + + /** + * Retrieves the public portion of a key plus its attributes. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @return the observable to the KeyBundle object + */ + public Observable getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { + return getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -1031,7 +1176,7 @@ public ServiceCall getKeyAsync(String vaultBaseUrl, String keyName, S * @param keyVersion The version of the key * @return the observable to the KeyBundle object */ - public Observable> getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { + public Observable> getKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1074,17 +1219,16 @@ private ServiceResponse getKeyDelegate(Response respons * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> object if successful. */ - public ServiceResponse> getKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1112,15 +1256,35 @@ public Observable>> call(String nextPageLink) { * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @return the observable to the List<KeyItem> object + * @return the observable to the PagedList<KeyItem> object */ - public Observable>> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName) { + public Observable> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName) { + return getKeyVersionsWithServiceResponseAsync(vaultBaseUrl, keyName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the observable to the PagedList<KeyItem> object + */ + public Observable>> getKeyVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String keyName) { return getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getKeyVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -1130,7 +1294,7 @@ public Observable>> call(ServiceResponse>> getKeyVersionsSinglePageAsync(final String vaultBaseUrl, final String keyName) { if (vaultBaseUrl == null) { @@ -1163,21 +1327,20 @@ public Observable>> call(Response re * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> object if successful. */ - public ServiceResponse> getKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1185,7 +1348,7 @@ public Page nextPage(String nextPageLink) throws RestException, IOExcep * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1206,16 +1369,37 @@ public Observable>> call(String nextPageLink) { * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param keyName The name of the key - * @param maxresults Maximum number of results to return. - * @return the observable to the List<KeyItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<KeyItem> object */ - public Observable>> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults) { + public Observable> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults) { + return getKeyVersionsWithServiceResponseAsync(vaultBaseUrl, keyName, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of the specified key. + * + * @param vaultBaseUrl The vault name, e.g. 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. + * @return the observable to the PagedList<KeyItem> object + */ + public Observable>> getKeyVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults) { return getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getKeyVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -1225,8 +1409,8 @@ public Observable>> call(ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net ServiceResponse> * @param keyName The name of the key - ServiceResponse> * @param maxresults Maximum number of results to return. - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getKeyVersionsSinglePageAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -1267,17 +1451,16 @@ private ServiceResponse> getKeyVersionsDelegate(Response> getKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -1303,15 +1486,34 @@ public Observable>> call(String nextPageLink) { * List keys in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @return the observable to the List<KeyItem> object + * @return the observable to the PagedList<KeyItem> object */ - public Observable>> getKeysAsync(final String vaultBaseUrl) { + public Observable> getKeysAsync(final String vaultBaseUrl) { + return getKeysWithServiceResponseAsync(vaultBaseUrl) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the PagedList<KeyItem> object + */ + public Observable>> getKeysWithServiceResponseAsync(final String vaultBaseUrl) { return getKeysSinglePageAsync(vaultBaseUrl) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getKeysNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeysNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -1320,7 +1522,7 @@ public Observable>> call(ServiceResponse>> getKeysSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { @@ -1349,28 +1551,27 @@ public Observable>> call(Response re * List keys in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> object if successful. */ - public ServiceResponse> getKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** * List keys in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -1390,16 +1591,36 @@ public Observable>> call(String nextPageLink) { * List keys in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. - * @return the observable to the List<KeyItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<KeyItem> object + */ + public Observable> getKeysAsync(final String vaultBaseUrl, final Integer maxresults) { + return getKeysWithServiceResponseAsync(vaultBaseUrl, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. + * @return the observable to the PagedList<KeyItem> object */ - public Observable>> getKeysAsync(final String vaultBaseUrl, final Integer maxresults) { + public Observable>> getKeysWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) { return getKeysSinglePageAsync(vaultBaseUrl, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getKeysNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeysNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -1408,8 +1629,8 @@ public Observable>> call(ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - ServiceResponse> * @param maxresults Maximum number of results to return. - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getKeysSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -1448,10 +1669,10 @@ private ServiceResponse> getKeysDelegate(Response backupKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return backupKeyAsync(vaultBaseUrl, keyName).toBlocking().single(); + public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().getBody(); } /** @@ -1463,7 +1684,7 @@ public ServiceResponse backupKey(String vaultBaseUrl, String ke * @return the {@link ServiceCall} object */ public ServiceCall backupKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { - return ServiceCall.create(backupKeyAsync(vaultBaseUrl, keyName), serviceCallback); + return ServiceCall.create(backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName), serviceCallback); } /** @@ -1473,7 +1694,23 @@ public ServiceCall backupKeyAsync(String vaultBaseUrl, String k * @param keyName The name of the key * @return the observable to the BackupKeyResult object */ - public Observable> backupKeyAsync(String vaultBaseUrl, String keyName) { + public Observable backupKeyAsync(String vaultBaseUrl, String keyName) { + return backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName).map(new Func1, BackupKeyResult>() { + @Override + public BackupKeyResult call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Requests that a backup of the specified key be downloaded to the client. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the observable to the BackupKeyResult object + */ + public Observable> backupKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1513,10 +1750,10 @@ private ServiceResponse backupKeyDelegate(Response restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return restoreKeyAsync(vaultBaseUrl, keyBundleBackup).toBlocking().single(); + public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup).toBlocking().single().getBody(); } /** @@ -1528,7 +1765,7 @@ public ServiceResponse restoreKey(String vaultBaseUrl, byte[] keyBund * @return the {@link ServiceCall} object */ public ServiceCall restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, final ServiceCallback serviceCallback) { - return ServiceCall.create(restoreKeyAsync(vaultBaseUrl, keyBundleBackup), serviceCallback); + return ServiceCall.create(restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup), serviceCallback); } /** @@ -1538,7 +1775,23 @@ public ServiceCall restoreKeyAsync(String vaultBaseUrl, byte[] keyBun * @param keyBundleBackup the backup blob associated with a key bundle * @return the observable to the KeyBundle object */ - public Observable> restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup) { + public Observable restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup) { + return restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Restores the backup key in to a vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyBundleBackup the backup blob associated with a key bundle + * @return the observable to the KeyBundle object + */ + public Observable> restoreKeyWithServiceResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1583,10 +1836,10 @@ private ServiceResponse restoreKeyDelegate(Response res * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult object if successful. */ - public ServiceResponse encrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return encryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); + public KeyOperationResult encrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().getBody(); } /** @@ -1601,7 +1854,26 @@ public ServiceResponse encrypt(String vaultBaseUrl, String k * @return the {@link ServiceCall} object */ public ServiceCall encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { - return ServiceCall.create(encryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + return ServiceCall.create(encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1, KeyOperationResult>() { + @Override + public KeyOperationResult call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -1614,7 +1886,7 @@ public ServiceCall encryptAsync(String vaultBaseUrl, String * @param value the Base64Url value * @return the observable to the KeyOperationResult object */ - public Observable> encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + public Observable> encryptWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1669,10 +1941,10 @@ private ServiceResponse encryptDelegate(Response decrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return decryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); + public KeyOperationResult decrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().getBody(); } /** @@ -1687,7 +1959,7 @@ public ServiceResponse decrypt(String vaultBaseUrl, String k * @return the {@link ServiceCall} object */ public ServiceCall decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { - return ServiceCall.create(decryptAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + return ServiceCall.create(decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); } /** @@ -1700,7 +1972,26 @@ public ServiceCall decryptAsync(String vaultBaseUrl, String * @param value the Base64Url value * @return the observable to the KeyOperationResult object */ - public Observable> decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + public Observable decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1, KeyOperationResult>() { + @Override + public KeyOperationResult call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> decryptWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1755,10 +2046,10 @@ private ServiceResponse decryptDelegate(Response sign(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return signAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); + public KeyOperationResult sign(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().getBody(); } /** @@ -1773,7 +2064,7 @@ public ServiceResponse sign(String vaultBaseUrl, String keyN * @return the {@link ServiceCall} object */ public ServiceCall signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { - return ServiceCall.create(signAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + return ServiceCall.create(signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); } /** @@ -1786,7 +2077,26 @@ public ServiceCall signAsync(String vaultBaseUrl, String key * @param value the Base64Url value * @return the observable to the KeyOperationResult object */ - public Observable> signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { + public Observable signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { + return signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1, KeyOperationResult>() { + @Override + public KeyOperationResult call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Creates a signature from a digest using the specified key in the vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> signWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1842,10 +2152,10 @@ private ServiceResponse signDelegate(Response * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyVerifyResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyVerifyResult object if successful. */ - public ServiceResponse verify(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return verifyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).toBlocking().single(); + public KeyVerifyResult verify(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).toBlocking().single().getBody(); } /** @@ -1861,7 +2171,27 @@ public ServiceResponse verify(String vaultBaseUrl, String keyNa * @return the {@link ServiceCall} object */ public ServiceCall verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { - return ServiceCall.create(verifyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature), serviceCallback); + return ServiceCall.create(verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature), serviceCallback); + } + + /** + * Verifies a signature using the specified key. + * + * @param vaultBaseUrl The vault name, e.g. 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. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param digest The digest used for signing + * @param signature The signature to be verified + * @return the observable to the KeyVerifyResult object + */ + public Observable verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { + return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).map(new Func1, KeyVerifyResult>() { + @Override + public KeyVerifyResult call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -1875,7 +2205,7 @@ public ServiceCall verifyAsync(String vaultBaseUrl, String keyN * @param signature The signature to be verified * @return the observable to the KeyVerifyResult object */ - public Observable> verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { + public Observable> verifyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1934,10 +2264,10 @@ private ServiceResponse verifyDelegate(Response r * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the KeyOperationResult object wrapped in {@link ServiceResponse} if successful. + * @return the KeyOperationResult object if successful. */ - public ServiceResponse wrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return wrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); + public KeyOperationResult wrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return wrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().getBody(); } /** @@ -1952,7 +2282,7 @@ public ServiceResponse wrapKey(String vaultBaseUrl, String k * @return the {@link ServiceCall} object */ public ServiceCall wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { - return ServiceCall.create(wrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + return ServiceCall.create(wrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); } /** @@ -1965,7 +2295,26 @@ public ServiceCall wrapKeyAsync(String vaultBaseUrl, String * @param value the Base64Url value * @return the observable to the KeyOperationResult object */ - public Observable> wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + public Observable wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return wrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1, KeyOperationResult>() { + @Override + public KeyOperationResult call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Wraps a symmetric key using the specified key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> wrapKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2020,10 +2369,10 @@ private ServiceResponse wrapKeyDelegate(Response unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return unwrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single(); + public KeyOperationResult unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().getBody(); } /** @@ -2038,7 +2387,7 @@ public ServiceResponse unwrapKey(String vaultBaseUrl, String * @return the {@link ServiceCall} object */ public ServiceCall unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { - return ServiceCall.create(unwrapKeyAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + return ServiceCall.create(unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); } /** @@ -2051,7 +2400,26 @@ public ServiceCall unwrapKeyAsync(String vaultBaseUrl, Strin * @param value the Base64Url value * @return the observable to the KeyOperationResult object */ - public Observable> unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + public Observable unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1, KeyOperationResult>() { + @Override + public KeyOperationResult call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Unwraps a symmetric key using the specified key in the vault that has initially been used for wrapping the key. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @param keyVersion The version of the key + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> unwrapKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2104,10 +2472,10 @@ private ServiceResponse unwrapKeyDelegate(Response setSecret(String vaultBaseUrl, String secretName, String value) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return setSecretAsync(vaultBaseUrl, secretName, value).toBlocking().single(); + public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value).toBlocking().single().getBody(); } /** @@ -2120,7 +2488,7 @@ public ServiceResponse setSecret(String vaultBaseUrl, String secre * @return the {@link ServiceCall} object */ public ServiceCall setSecretAsync(String vaultBaseUrl, String secretName, String value, final ServiceCallback serviceCallback) { - return ServiceCall.create(setSecretAsync(vaultBaseUrl, secretName, value), serviceCallback); + return ServiceCall.create(setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value), serviceCallback); } /** @@ -2131,7 +2499,24 @@ public ServiceCall setSecretAsync(String vaultBaseUrl, String secr * @param value The value of the secret * @return the observable to the SecretBundle object */ - public Observable> setSecretAsync(String vaultBaseUrl, String secretName, String value) { + public Observable setSecretAsync(String vaultBaseUrl, String secretName, String value) { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value).map(new Func1, SecretBundle>() { + @Override + public SecretBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Sets a secret in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param value The value of the secret + * @return the observable to the SecretBundle object + */ + public Observable> setSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String value) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2179,10 +2564,10 @@ public Observable> call(Response res * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle object if successful. */ - public ServiceResponse setSecret(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return setSecretAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes).toBlocking().single(); + public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes).toBlocking().single().getBody(); } /** @@ -2198,7 +2583,27 @@ public ServiceResponse setSecret(String vaultBaseUrl, String secre * @return the {@link ServiceCall} object */ public ServiceCall setSecretAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes, final ServiceCallback serviceCallback) { - return ServiceCall.create(setSecretAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes), serviceCallback); + return ServiceCall.create(setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes), serviceCallback); + } + + /** + * Sets a secret in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @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 + * @return the observable to the SecretBundle object + */ + public Observable setSecretAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes).map(new Func1, SecretBundle>() { + @Override + public SecretBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -2212,7 +2617,7 @@ public ServiceCall setSecretAsync(String vaultBaseUrl, String secr * @param secretAttributes The secret management attributes * @return the observable to the SecretBundle object */ - public Observable> setSecretAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) { + public Observable> setSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2262,10 +2667,10 @@ private ServiceResponse setSecretDelegate(Response r * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle object if successful. */ - public ServiceResponse deleteSecret(String vaultBaseUrl, String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return deleteSecretAsync(vaultBaseUrl, secretName).toBlocking().single(); + public SecretBundle deleteSecret(String vaultBaseUrl, String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteSecretWithServiceResponseAsync(vaultBaseUrl, secretName).toBlocking().single().getBody(); } /** @@ -2277,7 +2682,23 @@ public ServiceResponse deleteSecret(String vaultBaseUrl, String se * @return the {@link ServiceCall} object */ public ServiceCall deleteSecretAsync(String vaultBaseUrl, String secretName, final ServiceCallback serviceCallback) { - return ServiceCall.create(deleteSecretAsync(vaultBaseUrl, secretName), serviceCallback); + return ServiceCall.create(deleteSecretWithServiceResponseAsync(vaultBaseUrl, secretName), serviceCallback); + } + + /** + * Deletes a secret from the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @return the observable to the SecretBundle object + */ + public Observable deleteSecretAsync(String vaultBaseUrl, String secretName) { + return deleteSecretWithServiceResponseAsync(vaultBaseUrl, secretName).map(new Func1, SecretBundle>() { + @Override + public SecretBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -2287,7 +2708,7 @@ public ServiceCall deleteSecretAsync(String vaultBaseUrl, String s * @param secretName The name of the secret in the given vault * @return the observable to the SecretBundle object */ - public Observable> deleteSecretAsync(String vaultBaseUrl, String secretName) { + public Observable> deleteSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2328,10 +2749,10 @@ private ServiceResponse deleteSecretDelegate(Response updateSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateSecretAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single(); + public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single().getBody(); } /** @@ -2344,7 +2765,7 @@ public ServiceResponse updateSecret(String vaultBaseUrl, String se * @return the {@link ServiceCall} object */ public ServiceCall updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateSecretAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); + return ServiceCall.create(updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); } /** @@ -2355,7 +2776,24 @@ public ServiceCall updateSecretAsync(String vaultBaseUrl, String s * @param secretVersion The version of the secret * @return the observable to the SecretBundle object */ - public Observable> updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { + public Observable updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).map(new Func1, SecretBundle>() { + @Override + public SecretBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates the attributes associated with the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param secretVersion The version of the secret + * @return the observable to the SecretBundle object + */ + public Observable> updateSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String secretVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2402,10 +2840,10 @@ public Observable> call(Response res * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the SecretBundle object wrapped in {@link ServiceResponse} if successful. + * @return the SecretBundle object if successful. */ - public ServiceResponse updateSecret(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateSecretAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags).toBlocking().single(); + public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags).toBlocking().single().getBody(); } /** @@ -2421,7 +2859,27 @@ public ServiceResponse updateSecret(String vaultBaseUrl, String se * @return the {@link ServiceCall} object */ public ServiceCall updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateSecretAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags), serviceCallback); + return ServiceCall.create(updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags), serviceCallback); + } + + /** + * Updates the attributes associated with the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param secretVersion The version of the secret + * @param contentType Type of the secret value such as a password + * @param secretAttributes The secret management attributes + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the SecretBundle object + */ + public Observable updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags).map(new Func1, SecretBundle>() { + @Override + public SecretBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -2435,7 +2893,7 @@ public ServiceCall updateSecretAsync(String vaultBaseUrl, String s * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the SecretBundle object */ - public Observable> updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) { + public Observable> updateSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2485,10 +2943,23 @@ private ServiceResponse updateSecretDelegate(Response getSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getSecretAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single(); + public SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single().getBody(); + } + + /** + * Gets a secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param secretVersion The version of the secret + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { + return ServiceCall.create(getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); } /** @@ -2497,11 +2968,15 @@ public ServiceResponse getSecret(String vaultBaseUrl, String secre * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault * @param secretVersion The version of the secret - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object + * @return the observable to the SecretBundle object */ - public ServiceCall getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { - return ServiceCall.create(getSecretAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); + public Observable getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { + return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).map(new Func1, SecretBundle>() { + @Override + public SecretBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -2512,7 +2987,7 @@ public ServiceCall getSecretAsync(String vaultBaseUrl, String secr * @param secretVersion The version of the secret * @return the observable to the SecretBundle object */ - public Observable> getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { + public Observable> getSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String secretVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2554,17 +3029,16 @@ private ServiceResponse getSecretDelegate(Response r * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> object if successful. */ - public ServiceResponse> getSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -2590,15 +3064,34 @@ public Observable>> call(String nextPageLink) { * List secrets in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @return the observable to the List<SecretItem> object + * @return the observable to the PagedList<SecretItem> object + */ + public Observable> getSecretsAsync(final String vaultBaseUrl) { + return getSecretsWithServiceResponseAsync(vaultBaseUrl) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the PagedList<SecretItem> object */ - public Observable>> getSecretsAsync(final String vaultBaseUrl) { + public Observable>> getSecretsWithServiceResponseAsync(final String vaultBaseUrl) { return getSecretsSinglePageAsync(vaultBaseUrl) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getSecretsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -2607,7 +3100,7 @@ public Observable>> call(ServiceResponse>> getSecretsSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { @@ -2636,28 +3129,27 @@ public Observable>> call(Response * List secrets in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of secrets to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> object if successful. */ - public ServiceResponse> getSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** * List secrets in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of secrets to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -2677,16 +3169,36 @@ public Observable>> call(String nextPageLink) { * List secrets in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of secrets to return. - * @return the observable to the List<SecretItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<SecretItem> object + */ + public Observable> getSecretsAsync(final String vaultBaseUrl, final Integer maxresults) { + return getSecretsWithServiceResponseAsync(vaultBaseUrl, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. + * @return the observable to the PagedList<SecretItem> object */ - public Observable>> getSecretsAsync(final String vaultBaseUrl, final Integer maxresults) { + public Observable>> getSecretsWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) { return getSecretsSinglePageAsync(vaultBaseUrl, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getSecretsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -2695,8 +3207,8 @@ public Observable>> call(ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - ServiceResponse> * @param maxresults Maximum number of secrets to return. - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getSecretsSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -2735,17 +3247,16 @@ private ServiceResponse> getSecretsDelegate(Response> getSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -2773,15 +3284,35 @@ public Observable>> call(String nextPageLink) { * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault - * @return the observable to the List<SecretItem> object + * @return the observable to the PagedList<SecretItem> object + */ + public Observable> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName) { + return getSecretVersionsWithServiceResponseAsync(vaultBaseUrl, secretName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @return the observable to the PagedList<SecretItem> object */ - public Observable>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName) { + public Observable>> getSecretVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String secretName) { return getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getSecretVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -2791,7 +3322,7 @@ public Observable>> call(ServiceResponse>> getSecretVersionsSinglePageAsync(final String vaultBaseUrl, final String secretName) { if (vaultBaseUrl == null) { @@ -2824,21 +3355,20 @@ public Observable>> call(Response * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> object if successful. */ - public ServiceResponse> getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -2846,7 +3376,7 @@ public Page nextPage(String nextPageLink) throws RestException, IOEx * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -2867,16 +3397,37 @@ public Observable>> call(String nextPageLink) { * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param secretName The name of the secret in the given vault - * @param maxresults Maximum number of results to return. - * @return the observable to the List<SecretItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<SecretItem> object + */ + public Observable> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults) { + return getSecretVersionsWithServiceResponseAsync(vaultBaseUrl, secretName, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param secretName The name of the secret in the given vault + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<SecretItem> object */ - public Observable>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults) { + public Observable>> getSecretVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults) { return getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getSecretVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -2886,8 +3437,8 @@ public Observable>> call(ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net ServiceResponse> * @param secretName The name of the secret in the given vault - ServiceResponse> * @param maxresults Maximum number of results to return. - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getSecretVersionsSinglePageAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -2928,17 +3479,16 @@ private ServiceResponse> getSecretVersionsDelegate(Response * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> object if successful. */ - public ServiceResponse> getCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -2964,15 +3514,34 @@ public Observable>> call(String nextPageLi * List certificates in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @return the observable to the List<CertificateItem> object + * @return the observable to the PagedList<CertificateItem> object + */ + public Observable> getCertificatesAsync(final String vaultBaseUrl) { + return getCertificatesWithServiceResponseAsync(vaultBaseUrl) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the PagedList<CertificateItem> object */ - public Observable>> getCertificatesAsync(final String vaultBaseUrl) { + public Observable>> getCertificatesWithServiceResponseAsync(final String vaultBaseUrl) { return getCertificatesSinglePageAsync(vaultBaseUrl) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificatesNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -2981,7 +3550,7 @@ public Observable>> call(ServiceResponse

>> getCertificatesSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { @@ -3010,28 +3579,27 @@ public Observable>> call(Response> getCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** * List certificates in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -3051,16 +3619,36 @@ public Observable>> call(String nextPageLi * List certificates in the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. - * @return the observable to the List<CertificateItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<CertificateItem> object + */ + public Observable> getCertificatesAsync(final String vaultBaseUrl, final Integer maxresults) { + return getCertificatesWithServiceResponseAsync(vaultBaseUrl, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. + * @return the observable to the PagedList<CertificateItem> object */ - public Observable>> getCertificatesAsync(final String vaultBaseUrl, final Integer maxresults) { + public Observable>> getCertificatesWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) { return getCertificatesSinglePageAsync(vaultBaseUrl, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificatesNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -3069,8 +3657,8 @@ public Observable>> call(ServiceResponse

> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - ServiceResponse> * @param maxresults Maximum number of results to return. - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificatesSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -3109,10 +3697,10 @@ private ServiceResponse> getCertificatesDelegate(Respo * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle object if successful. */ - public ServiceResponse deleteCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return deleteCertificateAsync(vaultBaseUrl, certificateName).toBlocking().single(); + public CertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -3124,7 +3712,7 @@ public ServiceResponse deleteCertificate(String vaultBaseUrl, * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - return ServiceCall.create(deleteCertificateAsync(vaultBaseUrl, certificateName), serviceCallback); + return ServiceCall.create(deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); } /** @@ -3134,7 +3722,23 @@ public ServiceCall deleteCertificateAsync(String vaultBaseUrl * @param certificateName The name of the certificate in the given vault * @return the observable to the CertificateBundle object */ - public Observable> deleteCertificateAsync(String vaultBaseUrl, String certificateName) { + public Observable deleteCertificateAsync(String vaultBaseUrl, String certificateName) { + return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Deletes a certificate from the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @return the observable to the CertificateBundle object + */ + public Observable> deleteCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3174,10 +3778,10 @@ private ServiceResponse deleteCertificateDelegate(Response setCertificateContacts(String vaultBaseUrl, Contacts contacts) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return setCertificateContactsAsync(vaultBaseUrl, contacts).toBlocking().single(); + public Contacts setCertificateContacts(String vaultBaseUrl, Contacts contacts) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts).toBlocking().single().getBody(); } /** @@ -3189,7 +3793,23 @@ public ServiceResponse setCertificateContacts(String vaultBaseUrl, Con * @return the {@link ServiceCall} object */ public ServiceCall setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts, final ServiceCallback serviceCallback) { - return ServiceCall.create(setCertificateContactsAsync(vaultBaseUrl, contacts), serviceCallback); + return ServiceCall.create(setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts), serviceCallback); + } + + /** + * Sets the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param contacts The contacts for the vault certificates. + * @return the observable to the Contacts object + */ + public Observable setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts) { + return setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts).map(new Func1, Contacts>() { + @Override + public Contacts call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3199,7 +3819,7 @@ public ServiceCall setCertificateContactsAsync(String vaultBaseUrl, Co * @param contacts The contacts for the vault certificates. * @return the observable to the Contacts object */ - public Observable> setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts) { + public Observable> setCertificateContactsWithServiceResponseAsync(String vaultBaseUrl, Contacts contacts) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3239,10 +3859,10 @@ private ServiceResponse setCertificateContactsDelegate(Response getCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getCertificateContactsAsync(vaultBaseUrl).toBlocking().single(); + public Contacts getCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateContactsWithServiceResponseAsync(vaultBaseUrl).toBlocking().single().getBody(); } /** @@ -3253,7 +3873,22 @@ public ServiceResponse getCertificateContacts(String vaultBaseUrl) thr * @return the {@link ServiceCall} object */ public ServiceCall getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { - return ServiceCall.create(getCertificateContactsAsync(vaultBaseUrl), serviceCallback); + return ServiceCall.create(getCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); + } + + /** + * Gets the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the Contacts object + */ + public Observable getCertificateContactsAsync(String vaultBaseUrl) { + return getCertificateContactsWithServiceResponseAsync(vaultBaseUrl).map(new Func1, Contacts>() { + @Override + public Contacts call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3262,7 +3897,7 @@ public ServiceCall getCertificateContactsAsync(String vaultBaseUrl, fi * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @return the observable to the Contacts object */ - public Observable> getCertificateContactsAsync(String vaultBaseUrl) { + public Observable> getCertificateContactsWithServiceResponseAsync(String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3298,10 +3933,10 @@ private ServiceResponse getCertificateContactsDelegate(Response deleteCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return deleteCertificateContactsAsync(vaultBaseUrl).toBlocking().single(); + public Contacts deleteCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateContactsWithServiceResponseAsync(vaultBaseUrl).toBlocking().single().getBody(); } /** @@ -3312,7 +3947,7 @@ public ServiceResponse deleteCertificateContacts(String vaultBaseUrl) * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { - return ServiceCall.create(deleteCertificateContactsAsync(vaultBaseUrl), serviceCallback); + return ServiceCall.create(deleteCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); } /** @@ -3321,7 +3956,22 @@ public ServiceCall deleteCertificateContactsAsync(String vaultBaseUrl, * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @return the observable to the Contacts object */ - public Observable> deleteCertificateContactsAsync(String vaultBaseUrl) { + public Observable deleteCertificateContactsAsync(String vaultBaseUrl) { + return deleteCertificateContactsWithServiceResponseAsync(vaultBaseUrl).map(new Func1, Contacts>() { + @Override + public Contacts call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Deletes the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the Contacts object + */ + public Observable> deleteCertificateContactsWithServiceResponseAsync(String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3357,17 +4007,16 @@ private ServiceResponse deleteCertificateContactsDelegate(Response> getCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -3393,15 +4042,34 @@ public Observable>> call(String next * List certificate issuers for the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @return the observable to the List<CertificateIssuerItem> object + * @return the observable to the PagedList<CertificateIssuerItem> object + */ + public Observable> getCertificateIssuersAsync(final String vaultBaseUrl) { + return getCertificateIssuersWithServiceResponseAsync(vaultBaseUrl) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the observable to the PagedList<CertificateIssuerItem> object */ - public Observable>> getCertificateIssuersAsync(final String vaultBaseUrl) { + public Observable>> getCertificateIssuersWithServiceResponseAsync(final String vaultBaseUrl) { return getCertificateIssuersSinglePageAsync(vaultBaseUrl) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificateIssuersNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -3410,7 +4078,7 @@ public Observable>> call(ServiceResp * List certificate issuers for the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificateIssuersSinglePageAsync(final String vaultBaseUrl) { if (vaultBaseUrl == null) { @@ -3439,28 +4107,27 @@ public Observable>> call(Response> getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** * List certificate issuers for the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -3480,16 +4147,36 @@ public Observable>> call(String next * List certificate issuers for the specified vault. * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - * @param maxresults Maximum number of results to return. - * @return the observable to the List<CertificateIssuerItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<CertificateIssuerItem> object + */ + public Observable> getCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults) { + return getCertificateIssuersWithServiceResponseAsync(vaultBaseUrl, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. 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. + * @return the observable to the PagedList<CertificateIssuerItem> object */ - public Observable>> getCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults) { + public Observable>> getCertificateIssuersWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) { return getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificateIssuersNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -3498,8 +4185,8 @@ public Observable>> call(ServiceResp * List certificate issuers for the specified vault. * ServiceResponse> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net - ServiceResponse> * @param maxresults Maximum number of results to return. - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificateIssuersSinglePageAsync(final String vaultBaseUrl, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -3539,10 +4226,10 @@ private ServiceResponse> getCertificateIssuersDe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle object if successful. */ - public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider).toBlocking().single(); + public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).toBlocking().single().getBody(); } /** @@ -3555,7 +4242,24 @@ public ServiceResponse setCertificateIssuer(String vaultBaseUrl, S * @return the {@link ServiceCall} object */ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback serviceCallback) { - return ServiceCall.create(setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider), serviceCallback); + return ServiceCall.create(setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider), serviceCallback); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @return the observable to the IssuerBundle object + */ + public Observable setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider) { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).map(new Func1, IssuerBundle>() { + @Override + public IssuerBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3566,7 +4270,7 @@ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, * @param provider The issuer provider. * @return the observable to the IssuerBundle object */ - public Observable> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider) { + public Observable> setCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName, String provider) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3614,10 +4318,10 @@ public Observable> call(Response res * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle object if successful. */ - public ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single(); + public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single().getBody(); } /** @@ -3633,7 +4337,27 @@ public ServiceResponse setCertificateIssuer(String vaultBaseUrl, S * @return the {@link ServiceCall} object */ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { - return ServiceCall.create(setCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + return ServiceCall.create(setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @return the observable to the IssuerBundle object + */ + public Observable setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).map(new Func1, IssuerBundle>() { + @Override + public IssuerBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3647,7 +4371,7 @@ public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, * @param attributes Attributes of the issuer object. * @return the observable to the IssuerBundle object */ - public Observable> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { + public Observable> setCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3698,10 +4422,10 @@ private ServiceResponse setCertificateIssuerDelegate(Response updateCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateCertificateIssuerAsync(vaultBaseUrl, issuerName).toBlocking().single(); + public IssuerBundle updateCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().getBody(); } /** @@ -3713,7 +4437,23 @@ public ServiceResponse updateCertificateIssuer(String vaultBaseUrl * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateCertificateIssuerAsync(vaultBaseUrl, issuerName), serviceCallback); + return ServiceCall.create(updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object + */ + public Observable updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { + return updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).map(new Func1, IssuerBundle>() { + @Override + public IssuerBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3723,7 +4463,7 @@ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUr * @param issuerName The name of the issuer. * @return the observable to the IssuerBundle object */ - public Observable> updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { + public Observable> updateCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3769,10 +4509,10 @@ public Observable> call(Response res * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the IssuerBundle object wrapped in {@link ServiceResponse} if successful. + * @return the IssuerBundle object if successful. */ - public ServiceResponse updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single(); + public IssuerBundle updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single().getBody(); } /** @@ -3788,7 +4528,27 @@ public ServiceResponse updateCertificateIssuer(String vaultBaseUrl * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateCertificateIssuerAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + return ServiceCall.create(updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @param credentials The credentials to be used for the issuer. + * @param organizationDetails Details of the organization as provided to the issuer. + * @param attributes Attributes of the issuer object. + * @return the observable to the IssuerBundle object + */ + public Observable updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { + return updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).map(new Func1, IssuerBundle>() { + @Override + public IssuerBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3802,7 +4562,7 @@ public ServiceCall updateCertificateIssuerAsync(String vaultBaseUr * @param attributes Attributes of the issuer object. * @return the observable to the IssuerBundle object */ - public Observable> updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { + public Observable> updateCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3850,10 +4610,10 @@ private ServiceResponse updateCertificateIssuerDelegate(Response getCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getCertificateIssuerAsync(vaultBaseUrl, issuerName).toBlocking().single(); + public IssuerBundle getCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().getBody(); } /** @@ -3865,7 +4625,23 @@ public ServiceResponse getCertificateIssuer(String vaultBaseUrl, S * @return the {@link ServiceCall} object */ public ServiceCall getCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { - return ServiceCall.create(getCertificateIssuerAsync(vaultBaseUrl, issuerName), serviceCallback); + return ServiceCall.create(getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Gets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object + */ + public Observable getCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { + return getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).map(new Func1, IssuerBundle>() { + @Override + public IssuerBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3875,7 +4651,7 @@ public ServiceCall getCertificateIssuerAsync(String vaultBaseUrl, * @param issuerName The name of the issuer. * @return the observable to the IssuerBundle object */ - public Observable> getCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { + public Observable> getCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3915,10 +4691,10 @@ private ServiceResponse getCertificateIssuerDelegate(Response deleteCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return deleteCertificateIssuerAsync(vaultBaseUrl, issuerName).toBlocking().single(); + public IssuerBundle deleteCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().getBody(); } /** @@ -3930,7 +4706,23 @@ public ServiceResponse deleteCertificateIssuer(String vaultBaseUrl * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { - return ServiceCall.create(deleteCertificateIssuerAsync(vaultBaseUrl, issuerName), serviceCallback); + return ServiceCall.create(deleteCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Deletes the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object + */ + public Observable deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { + return deleteCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).map(new Func1, IssuerBundle>() { + @Override + public IssuerBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3940,7 +4732,7 @@ public ServiceCall deleteCertificateIssuerAsync(String vaultBaseUr * @param issuerName The name of the issuer. * @return the observable to the IssuerBundle object */ - public Observable> deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { + public Observable> deleteCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3980,10 +4772,10 @@ private ServiceResponse deleteCertificateIssuerDelegate(Response createCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return createCertificateAsync(vaultBaseUrl, certificateName).toBlocking().single(); + public CertificateOperation createCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -3995,7 +4787,23 @@ public ServiceResponse createCertificate(String vaultBaseU * @return the {@link ServiceCall} object */ public ServiceCall createCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - return ServiceCall.create(createCertificateAsync(vaultBaseUrl, certificateName), serviceCallback); + return ServiceCall.create(createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Creates a new certificate version. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the CertificateOperation object + */ + public Observable createCertificateAsync(String vaultBaseUrl, String certificateName) { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1, CertificateOperation>() { + @Override + public CertificateOperation call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4005,7 +4813,7 @@ public ServiceCall createCertificateAsync(String vaultBase * @param certificateName The name of the certificate * @return the observable to the CertificateOperation object */ - public Observable> createCertificateAsync(String vaultBaseUrl, String certificateName) { + public Observable> createCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4048,10 +4856,10 @@ public Observable> call(Response createCertificate(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return createCertificateAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags).toBlocking().single(); + public CertificateOperation createCertificate(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags).toBlocking().single().getBody(); } /** @@ -4066,7 +4874,26 @@ public ServiceResponse createCertificate(String vaultBaseU * @return the {@link ServiceCall} object */ public ServiceCall createCertificateAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(createCertificateAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags), serviceCallback); + return ServiceCall.create(createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Creates a new certificate version. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param certificatePolicy The management policy for the certificate + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateOperation object + */ + public Observable createCertificateAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags).map(new Func1, CertificateOperation>() { + @Override + public CertificateOperation call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4079,7 +4906,7 @@ public ServiceCall createCertificateAsync(String vaultBase * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the CertificateOperation object */ - public Observable> createCertificateAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + public Observable> createCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4127,10 +4954,23 @@ private ServiceResponse createCertificateDelegate(Response * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle object if successful. + */ + public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).toBlocking().single().getBody(); + } + + /** + * Imports a certificate into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object */ - public ServiceResponse importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).toBlocking().single(); + public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, final ServiceCallback serviceCallback) { + return ServiceCall.create(importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate), serviceCallback); } /** @@ -4139,11 +4979,15 @@ public ServiceResponse importCertificate(String vaultBaseUrl, * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. - * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @return the {@link ServiceCall} object + * @return the observable to the CertificateBundle object */ - public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, final ServiceCallback serviceCallback) { - return ServiceCall.create(importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate), serviceCallback); + public Observable importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4154,7 +4998,7 @@ public ServiceCall importCertificateAsync(String vaultBaseUrl * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. * @return the observable to the CertificateBundle object */ - public Observable> importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { + public Observable> importCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4205,10 +5049,10 @@ public Observable> call(Response importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).toBlocking().single(); + public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).toBlocking().single().getBody(); } /** @@ -4225,7 +5069,28 @@ public ServiceResponse importCertificate(String vaultBaseUrl, * @return the {@link ServiceCall} object */ public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(importCertificateAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags), serviceCallback); + return ServiceCall.create(importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Imports a certificate into the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption + * @param certificatePolicy The management policy for the certificate + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateBundle object + */ + public Observable importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4240,7 +5105,7 @@ public ServiceCall importCertificateAsync(String vaultBaseUrl * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the CertificateBundle object */ - public Observable> importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + public Observable> importCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4292,17 +5157,16 @@ private ServiceResponse importCertificateDelegate(Response> getCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -4330,15 +5194,35 @@ public Observable>> call(String nextPageLi * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate - * @return the observable to the List<CertificateItem> object + * @return the observable to the PagedList<CertificateItem> object + */ + public Observable> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName) { + return getCertificateVersionsWithServiceResponseAsync(vaultBaseUrl, certificateName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the PagedList<CertificateItem> object */ - public Observable>> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName) { + public Observable>> getCertificateVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String certificateName) { return getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificateVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -4348,7 +5232,7 @@ public Observable>> call(ServiceResponse

>> getCertificateVersionsSinglePageAsync(final String vaultBaseUrl, final String certificateName) { if (vaultBaseUrl == null) { @@ -4381,21 +5265,20 @@ public Observable>> call(Response> getCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -4403,7 +5286,7 @@ public Page nextPage(String nextPageLink) throws RestException, * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate - * @param maxresults Maximum number of results to return. + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ @@ -4424,16 +5307,37 @@ public Observable>> call(String nextPageLi * * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net * @param certificateName The name of the certificate - * @param maxresults Maximum number of results to return. - * @return the observable to the List<CertificateItem> object + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<CertificateItem> object + */ + public Observable> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { + return getCertificateVersionsWithServiceResponseAsync(vaultBaseUrl, certificateName, maxresults) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the observable to the PagedList<CertificateItem> object */ - public Observable>> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { + public Observable>> getCertificateVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { return getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificateVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -4443,8 +5347,8 @@ public Observable>> call(ServiceResponse

> * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net ServiceResponse> * @param certificateName The name of the certificate - ServiceResponse> * @param maxresults Maximum number of results to return. - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + ServiceResponse> * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results. + * @return the PagedList<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificateVersionsSinglePageAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { if (vaultBaseUrl == null) { @@ -4486,10 +5390,10 @@ private ServiceResponse> getCertificateVersionsDelegat * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificatePolicy object wrapped in {@link ServiceResponse} if successful. + * @return the CertificatePolicy object if successful. */ - public ServiceResponse getCertificatePolicy(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getCertificatePolicyAsync(vaultBaseUrl, certificateName).toBlocking().single(); + public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -4501,7 +5405,23 @@ public ServiceResponse getCertificatePolicy(String vaultBaseU * @return the {@link ServiceCall} object */ public ServiceCall getCertificatePolicyAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - return ServiceCall.create(getCertificatePolicyAsync(vaultBaseUrl, certificateName), serviceCallback); + return ServiceCall.create(getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Gets the policy for a certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault. + * @return the observable to the CertificatePolicy object + */ + public Observable getCertificatePolicyAsync(String vaultBaseUrl, String certificateName) { + return getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1, CertificatePolicy>() { + @Override + public CertificatePolicy call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4511,7 +5431,7 @@ public ServiceCall getCertificatePolicyAsync(String vaultBase * @param certificateName The name of the certificate in the given vault. * @return the observable to the CertificatePolicy object */ - public Observable> getCertificatePolicyAsync(String vaultBaseUrl, String certificateName) { + public Observable> getCertificatePolicyWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4552,10 +5472,10 @@ private ServiceResponse getCertificatePolicyDelegate(Response * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificatePolicy object wrapped in {@link ServiceResponse} if successful. + * @return the CertificatePolicy object if successful. */ - public ServiceResponse updateCertificatePolicy(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateCertificatePolicyAsync(vaultBaseUrl, certificateName, certificatePolicy).toBlocking().single(); + public CertificatePolicy updateCertificatePolicy(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy).toBlocking().single().getBody(); } /** @@ -4568,7 +5488,24 @@ public ServiceResponse updateCertificatePolicy(String vaultBa * @return the {@link ServiceCall} object */ public ServiceCall updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateCertificatePolicyAsync(vaultBaseUrl, certificateName, certificatePolicy), serviceCallback); + return ServiceCall.create(updateCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy), serviceCallback); + } + + /** + * Updates the policy for a certificate. Set appropriate members in the certificatePolicy that must be updated. Leave others as null. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault. + * @param certificatePolicy The policy for the certificate. + * @return the observable to the CertificatePolicy object + */ + public Observable updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) { + return updateCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy).map(new Func1, CertificatePolicy>() { + @Override + public CertificatePolicy call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4579,7 +5516,7 @@ public ServiceCall updateCertificatePolicyAsync(String vaultB * @param certificatePolicy The policy for the certificate. * @return the observable to the CertificatePolicy object */ - public Observable> updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) { + public Observable> updateCertificatePolicyWithServiceResponseAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4624,10 +5561,10 @@ private ServiceResponse updateCertificatePolicyDelegate(Respo * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle object if successful. */ - public ServiceResponse updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single(); + public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single().getBody(); } /** @@ -4640,7 +5577,24 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + return ServiceCall.create(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + } + + /** + * Updates the attributes associated with the specified certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @param certificateVersion The version of the certificate + * @return the observable to the CertificateBundle object + */ + public Observable updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4651,7 +5605,7 @@ public ServiceCall updateCertificateAsync(String vaultBaseUrl * @param certificateVersion The version of the certificate * @return the observable to the CertificateBundle object */ - public Observable> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { + public Observable> updateCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4698,10 +5652,10 @@ public Observable> call(Response updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).toBlocking().single(); + public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).toBlocking().single().getBody(); } /** @@ -4717,7 +5671,27 @@ public ServiceResponse updateCertificate(String vaultBaseUrl, * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateCertificateAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags), serviceCallback); + return ServiceCall.create(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Updates the attributes associated with the specified certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @param certificateVersion The version of the certificate + * @param certificatePolicy The management policy for the certificate + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateBundle object + */ + public Observable updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4731,7 +5705,7 @@ public ServiceCall updateCertificateAsync(String vaultBaseUrl * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the CertificateBundle object */ - public Observable> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + public Observable> updateCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4782,10 +5756,10 @@ private ServiceResponse updateCertificateDelegate(Response getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getCertificateAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single(); + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single().getBody(); } /** @@ -4798,7 +5772,24 @@ public ServiceResponse getCertificate(String vaultBaseUrl, St * @return the {@link ServiceCall} object */ public ServiceCall getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { - return ServiceCall.create(getCertificateAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + return ServiceCall.create(getCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + } + + /** + * Gets a Certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate in the given vault + * @param certificateVersion The version of the certificate + * @return the observable to the CertificateBundle object + */ + public Observable getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { + return getCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4809,7 +5800,7 @@ public ServiceCall getCertificateAsync(String vaultBaseUrl, S * @param certificateVersion The version of the certificate * @return the observable to the CertificateBundle object */ - public Observable> getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { + public Observable> getCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4853,10 +5844,10 @@ private ServiceResponse getCertificateDelegate(Response updateCertificateOperation(String vaultBaseUrl, String certificateName, boolean cancellationRequested) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return updateCertificateOperationAsync(vaultBaseUrl, certificateName, cancellationRequested).toBlocking().single(); + public CertificateOperation updateCertificateOperation(String vaultBaseUrl, String certificateName, boolean cancellationRequested) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested).toBlocking().single().getBody(); } /** @@ -4869,7 +5860,7 @@ public ServiceResponse updateCertificateOperation(String v * @return the {@link ServiceCall} object */ public ServiceCall updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested, final ServiceCallback serviceCallback) { - return ServiceCall.create(updateCertificateOperationAsync(vaultBaseUrl, certificateName, cancellationRequested), serviceCallback); + return ServiceCall.create(updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested), serviceCallback); } /** @@ -4880,7 +5871,24 @@ public ServiceCall updateCertificateOperationAsync(String * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. * @return the observable to the CertificateOperation object */ - public Observable> updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { + public Observable updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { + return updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested).map(new Func1, CertificateOperation>() { + @Override + public CertificateOperation call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates a certificate operation. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. + * @return the observable to the CertificateOperation object + */ + public Observable> updateCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4922,10 +5930,10 @@ private ServiceResponse updateCertificateOperationDelegate * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateOperation object if successful. */ - public ServiceResponse getCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return getCertificateOperationAsync(vaultBaseUrl, certificateName).toBlocking().single(); + public CertificateOperation getCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -4937,7 +5945,23 @@ public ServiceResponse getCertificateOperation(String vaul * @return the {@link ServiceCall} object */ public ServiceCall getCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - return ServiceCall.create(getCertificateOperationAsync(vaultBaseUrl, certificateName), serviceCallback); + return ServiceCall.create(getCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Gets the certificate operation response. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the CertificateOperation object + */ + public Observable getCertificateOperationAsync(String vaultBaseUrl, String certificateName) { + return getCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1, CertificateOperation>() { + @Override + public CertificateOperation call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -4947,7 +5971,7 @@ public ServiceCall getCertificateOperationAsync(String vau * @param certificateName The name of the certificate * @return the observable to the CertificateOperation object */ - public Observable> getCertificateOperationAsync(String vaultBaseUrl, String certificateName) { + public Observable> getCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4987,10 +6011,10 @@ private ServiceResponse getCertificateOperationDelegate(Re * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateOperation object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateOperation object if successful. */ - public ServiceResponse deleteCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return deleteCertificateOperationAsync(vaultBaseUrl, certificateName).toBlocking().single(); + public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -5002,7 +6026,23 @@ public ServiceResponse deleteCertificateOperation(String v * @return the {@link ServiceCall} object */ public ServiceCall deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { - return ServiceCall.create(deleteCertificateOperationAsync(vaultBaseUrl, certificateName), serviceCallback); + return ServiceCall.create(deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Deletes the certificate operation. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @return the observable to the CertificateOperation object + */ + public Observable deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName) { + return deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1, CertificateOperation>() { + @Override + public CertificateOperation call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -5012,7 +6052,7 @@ public ServiceCall deleteCertificateOperationAsync(String * @param certificateName The name of the certificate * @return the observable to the CertificateOperation object */ - public Observable> deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName) { + public Observable> deleteCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5053,10 +6093,10 @@ private ServiceResponse deleteCertificateOperationDelegate * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @return the CertificateBundle object if successful. */ - public ServiceResponse mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates).toBlocking().single(); + public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates).toBlocking().single().getBody(); } /** @@ -5069,7 +6109,24 @@ public ServiceResponse mergeCertificate(String vaultBaseUrl, * @return the {@link ServiceCall} object */ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, final ServiceCallback serviceCallback) { - return ServiceCall.create(mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates), serviceCallback); + return ServiceCall.create(mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates), serviceCallback); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param x509Certificates The certificate or the certificate chain to merge + * @return the observable to the CertificateBundle object + */ + public Observable mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates) { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -5080,7 +6137,7 @@ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, * @param x509Certificates The certificate or the certificate chain to merge * @return the observable to the CertificateBundle object */ - public Observable> mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates) { + public Observable> mergeCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, List x509Certificates) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5126,10 +6183,10 @@ public Observable> call(Response mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { - return mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags).toBlocking().single(); + public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags).toBlocking().single().getBody(); } /** @@ -5144,7 +6201,26 @@ public ServiceResponse mergeCertificate(String vaultBaseUrl, * @return the {@link ServiceCall} object */ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { - return ServiceCall.create(mergeCertificateAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags), serviceCallback); + return ServiceCall.create(mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags), serviceCallback); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * @param x509Certificates The certificate or the certificate chain to merge + * @param certificateAttributes The attributes of the certificate (optional) + * @param tags Application-specific metadata in the form of key-value pairs + * @return the observable to the CertificateBundle object + */ + public Observable mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -5157,7 +6233,7 @@ public ServiceCall mergeCertificateAsync(String vaultBaseUrl, * @param tags Application-specific metadata in the form of key-value pairs * @return the observable to the CertificateBundle object */ - public Observable> mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { + public Observable> mergeCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5206,17 +6282,16 @@ private ServiceResponse mergeCertificateDelegate(Response> getKeyVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getKeyVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5243,15 +6318,34 @@ public Observable>> call(String nextPageLink) { * List the versions of the specified key. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<KeyItem> object + * @return the observable to the PagedList<KeyItem> object + */ + public Observable> getKeyVersionsNextAsync(final String nextPageLink) { + return getKeyVersionsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of the specified key. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<KeyItem> object */ - public Observable>> getKeyVersionsNextAsync(final String nextPageLink) { + public Observable>> getKeyVersionsNextWithServiceResponseAsync(final String nextPageLink) { return getKeyVersionsNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getKeyVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5260,7 +6354,7 @@ public Observable>> call(ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getKeyVersionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { @@ -5294,17 +6388,16 @@ private ServiceResponse> getKeyVersionsNextDelegate(Response> getKeysNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getKeysNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getKeysNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5331,15 +6424,34 @@ public Observable>> call(String nextPageLink) { * List keys in the specified vault. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<KeyItem> object + * @return the observable to the PagedList<KeyItem> object + */ + public Observable> getKeysNextAsync(final String nextPageLink) { + return getKeysNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<KeyItem> object */ - public Observable>> getKeysNextAsync(final String nextPageLink) { + public Observable>> getKeysNextWithServiceResponseAsync(final String nextPageLink) { return getKeysNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getKeysNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeysNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5348,7 +6460,7 @@ public Observable>> call(ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<KeyItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<KeyItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getKeysNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { @@ -5382,17 +6494,16 @@ private ServiceResponse> getKeysNextDelegate(Response> getSecretsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getSecretsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5419,15 +6530,34 @@ public Observable>> call(String nextPageLink) { * List secrets in the specified vault. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<SecretItem> object + * @return the observable to the PagedList<SecretItem> object + */ + public Observable> getSecretsNextAsync(final String nextPageLink) { + return getSecretsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List secrets in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<SecretItem> object */ - public Observable>> getSecretsNextAsync(final String nextPageLink) { + public Observable>> getSecretsNextWithServiceResponseAsync(final String nextPageLink) { return getSecretsNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getSecretsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5436,7 +6566,7 @@ public Observable>> call(ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getSecretsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { @@ -5470,17 +6600,16 @@ private ServiceResponse> getSecretsNextDelegate(Response> getSecretVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getSecretVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5507,15 +6636,34 @@ public Observable>> call(String nextPageLink) { * List the versions of the specified secret. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<SecretItem> object + * @return the observable to the PagedList<SecretItem> object */ - public Observable>> getSecretVersionsNextAsync(final String nextPageLink) { + public Observable> getSecretVersionsNextAsync(final String nextPageLink) { + return getSecretVersionsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<SecretItem> object + */ + public Observable>> getSecretVersionsNextWithServiceResponseAsync(final String nextPageLink) { return getSecretVersionsNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getSecretVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5524,7 +6672,7 @@ public Observable>> call(ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<SecretItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<SecretItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getSecretVersionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { @@ -5558,17 +6706,16 @@ private ServiceResponse> getSecretVersionsNextDelegate(Resp * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> object if successful. */ - public ServiceResponse> getCertificatesNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificatesNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5595,15 +6742,34 @@ public Observable>> call(String nextPageLi * List certificates in the specified vault. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<CertificateItem> object + * @return the observable to the PagedList<CertificateItem> object + */ + public Observable> getCertificatesNextAsync(final String nextPageLink) { + return getCertificatesNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List certificates in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<CertificateItem> object */ - public Observable>> getCertificatesNextAsync(final String nextPageLink) { + public Observable>> getCertificatesNextWithServiceResponseAsync(final String nextPageLink) { return getCertificatesNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificatesNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5612,7 +6778,7 @@ public Observable>> call(ServiceResponse

> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificatesNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { @@ -5646,17 +6812,16 @@ private ServiceResponse> getCertificatesNextDelegate(R * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateIssuerItem> object if successful. */ - public ServiceResponse> getCertificateIssuersNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificateIssuersNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5683,15 +6848,34 @@ public Observable>> call(String next * List certificate issuers for the specified vault. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<CertificateIssuerItem> object + * @return the observable to the PagedList<CertificateIssuerItem> object + */ + public Observable> getCertificateIssuersNextAsync(final String nextPageLink) { + return getCertificateIssuersNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<CertificateIssuerItem> object */ - public Observable>> getCertificateIssuersNextAsync(final String nextPageLink) { + public Observable>> getCertificateIssuersNextWithServiceResponseAsync(final String nextPageLink) { return getCertificateIssuersNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificateIssuersNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5700,7 +6884,7 @@ public Observable>> call(ServiceResp * List certificate issuers for the specified vault. * ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateIssuerItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificateIssuersNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { @@ -5734,17 +6918,16 @@ private ServiceResponse> getCertificateIssuersNe * @throws KeyVaultErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> object if successful. */ - public ServiceResponse> getCertificateVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public PagedList getCertificateVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { ServiceResponse> response = getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); - PagedList pagedList = new PagedList(response.getBody()) { + return new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse>(pagedList, response.getResponse()); } /** @@ -5771,15 +6954,34 @@ public Observable>> call(String nextPageLi * List the versions of a certificate. * * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the observable to the List<CertificateItem> object + * @return the observable to the PagedList<CertificateItem> object + */ + public Observable> getCertificateVersionsNextAsync(final String nextPageLink) { + return getCertificateVersionsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * List the versions of a certificate. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<CertificateItem> object */ - public Observable>> getCertificateVersionsNextAsync(final String nextPageLink) { + public Observable>> getCertificateVersionsNextWithServiceResponseAsync(final String nextPageLink) { return getCertificateVersionsNextSinglePageAsync(nextPageLink) .concatMap(new Func1>, Observable>>>() { @Override public Observable>> call(ServiceResponse> page) { String nextPageLink = page.getBody().getNextPageLink(); - return getCertificateVersionsNextSinglePageAsync(nextPageLink); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(nextPageLink)); } }); } @@ -5788,7 +6990,7 @@ public Observable>> call(ServiceResponse

> * @param nextPageLink The NextLink from the previous successful call to List operation. - * @return the List<CertificateItem> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<CertificateItem> object wrapped in {@link ServiceResponse} if successful. */ public Observable>> getCertificateVersionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java index 07fff30be2e88..e8353e0708742 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java @@ -116,17 +116,6 @@ public Boolean managed() { return this.managed; } - /** - * Set the managed value. - * - * @param managed the managed value to set - * @return the KeyBundle object itself. - */ - public KeyBundle withManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * The key identifier. * @return identifier for the key diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java index 57f669af5a4b7..f54b847cd02f7 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java @@ -110,17 +110,6 @@ public Boolean managed() { return this.managed; } - /** - * Set the managed value. - * - * @param managed the managed value to set - * @return the KeyItem object itself. - */ - public KeyItem withManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * The key identifier. * @return The Identifier value diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java index 2035765e09b95..f5648ae67eb13 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java @@ -172,17 +172,6 @@ public String kid() { return this.kid; } - /** - * Set the kid value. - * - * @param kid the kid value to set - * @return the SecretBundle object itself. - */ - public SecretBundle withKid(String kid) { - this.kid = kid; - return this; - } - /** * Get the managed value. * @@ -192,17 +181,6 @@ public Boolean managed() { return this.managed; } - /** - * Set the managed value. - * - * @param managed the managed value to set - * @return the SecretBundle object itself. - */ - public SecretBundle withManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * the secret identifier. * @return The Identifier value diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java index 9c4c31e91d44a..00bd3528dc4a0 100755 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java @@ -135,17 +135,6 @@ public Boolean managed() { return this.managed; } - /** - * Set the managed value. - * - * @param managed the managed value to set - * @return the SecretItem object itself. - */ - public SecretItem withManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * the secret identifier. * @return The Identifier value diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java index 8e4b7c7dced0f..833f167d399ff 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -150,7 +150,7 @@ public void createSelfSignedCertificatePkcs12() throws Exception { .withTags(sTags) .build(); - CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest).getBody(); + CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest); Assert.assertNotNull(certificateOperation); Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); @@ -167,12 +167,12 @@ public void createSelfSignedCertificatePkcs12() throws Exception { // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()); Assert.assertTrue(secret.managed()); // Retrieve the key backing the certificate KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier(); - KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier()).getBody(); + KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier()); Assert.assertTrue(keyBundle.managed()); // Load the secret into a KeyStore @@ -182,7 +182,7 @@ public void createSelfSignedCertificatePkcs12() throws Exception { // Validate the certificate and key in the KeyStore validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); Assert.assertNotNull(deletedCertificateBundle); try { keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); @@ -224,7 +224,7 @@ public void createSelfSignedCertificatePem() throws Exception { new CreateCertificateRequest .Builder(vaultUri, certificateName) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); Assert.assertNotNull(certificateOperation); Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); @@ -234,7 +234,7 @@ public void createSelfSignedCertificatePem() throws Exception { validatePem(certificateBundle, subjectName); - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); Assert.assertNotNull(deletedCertificateBundle); try { @@ -277,7 +277,7 @@ public void createCertificatePkcs12() throws Exception { .Builder(getVaultUri(),certificateIssuerName, ISSUER_TEST) .withCredentials(credentials) .withOrganizationDetails(organizationDetails) - .build()).getBody(); + .build()); validateCertificateIssuer(createdCertificateIssuer, certificateIssuerName); @@ -305,7 +305,7 @@ public void createCertificatePkcs12() throws Exception { new CreateCertificateRequest .Builder(vaultUri, certificateName) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); Assert.assertNotNull(certificateOperation); Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); @@ -321,7 +321,7 @@ public void createCertificatePkcs12() throws Exception { // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()); Assert.assertTrue(secret.managed()); // Load the secret into a KeyStore @@ -331,7 +331,7 @@ public void createCertificatePkcs12() throws Exception { // Validate the certificate and key in the KeyStore validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); Assert.assertNotNull(deletedCertificateBundle); try { @@ -374,7 +374,7 @@ public void createCertificatePem() throws Exception { .Builder(getVaultUri(), certificateIssuerName, ISSUER_TEST) .withCredentials(credentials) .withOrganizationDetails(organizationDetails) - .build()).getBody(); + .build()); validateCertificateIssuer(createdCertificateIssuer, certificateIssuerName); // Set content type to indicate the certificate is PEM format. @@ -401,7 +401,7 @@ public void createCertificatePem() throws Exception { new CreateCertificateRequest .Builder(vaultUri, certificateName) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); Assert.assertNotNull(certificateOperation); Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); @@ -411,7 +411,7 @@ public void createCertificatePem() throws Exception { validatePem(certificateBundle, subjectName); - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); Assert.assertNotNull(deletedCertificateBundle); try { @@ -458,16 +458,16 @@ public void createCsr() throws InterruptedException, ExecutionException, KeyVaul new CreateCertificateRequest .Builder(vaultUri, certificateName) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); Assert.assertNotNull(certificateOperation); Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); Assert.assertNotNull(certificateOperation.csr()); - String csr = keyVaultClient.getPendingCertificateSigningRequest(vaultUri, certificateName).getBody(); + String csr = keyVaultClient.getPendingCertificateSigningRequest(vaultUri, certificateName); Assert.assertNotNull(csr); - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); Assert.assertNotNull(deletedCertificateBundle); try { @@ -511,18 +511,18 @@ public void certificateAsyncRequestCancellation() throws KeyVaultErrorException, new CreateCertificateRequest .Builder(vaultUri, certificateName) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); CertificateOperation cancelledCertificateOperation = keyVaultClient.updateCertificateOperation( new UpdateCertificateOperationRequest .Builder(vaultUri, certificateName, true) - .build()).getBody(); + .build()); Assert.assertNotNull(cancelledCertificateOperation); Assert.assertTrue(cancelledCertificateOperation.cancellationRequested()); - keyVaultClient.deleteCertificateOperation(getVaultUri(), certificateName).getBody(); - keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + keyVaultClient.deleteCertificateOperation(getVaultUri(), certificateName); + keyVaultClient.deleteCertificate(getVaultUri(), certificateName); } /** @@ -547,7 +547,7 @@ public void importCertificatePkcs12() throws Exception { .withPolicy(certificatePolicy) .withAttributes(attribute) .withTags(sTags) - .build()).getBody(); + .build()); // Validate the certificate bundle created validateCertificateBundle(certificateBundle, certificatePolicy); @@ -562,7 +562,7 @@ public void importCertificatePkcs12() throws Exception { // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()); Assert.assertTrue(secret.managed()); // Load the secret into a KeyStore @@ -572,7 +572,7 @@ public void importCertificatePkcs12() throws Exception { // Validate the certificate and key in the KeyStore validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); - CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName).getBody(); + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); try { keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); @@ -601,7 +601,7 @@ public void certificateUpdate() throws Exception { .Builder(vaultUri, certificateName, certificateContent) .withPassword(certificatePassword) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); Attributes attribute = new CertificateAttributes() @@ -612,7 +612,7 @@ public void certificateUpdate() throws Exception { .Builder(vaultUri, certificateName) .withAttributes(attribute.withEnabled(false)) .withTags(sTags) - .build()).getBody(); + .build()); Assert.assertEquals(attribute.enabled(), updatedCertBundle.attributes().enabled()); Assert.assertEquals(sTags.toString(), updatedCertBundle.tags().toString()); @@ -621,10 +621,10 @@ public void certificateUpdate() throws Exception { new UpdateCertificatePolicyRequest .Builder(vaultUri, certificateName) .withPolicy(certificatePolicyUpdate) - .build()).getBody(); + .build()); Assert.assertEquals(certificatePolicyUpdate.issuerReference().name(), updatedCertificatePolicy.issuerReference().name()); - CertificatePolicy policy = keyVaultClient.getCertificatePolicy(vaultUri, certificateName).getBody(); + CertificatePolicy policy = keyVaultClient.getCertificatePolicy(vaultUri, certificateName); Assert.assertEquals(certificatePolicyUpdate.issuerReference().name(), policy.issuerReference().name()); keyVaultClient.deleteCertificate(getVaultUri(), certificateName); @@ -655,7 +655,7 @@ public void listCertificates() throws Exception { .Builder(getVaultUri(), certificateName + i, certificateContent) .withPassword(certificatePassword) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); CertificateIdentifier id = certificateBundle.certificateIdentifier(); certificates.add(id.baseIdentifier()); break; @@ -671,7 +671,7 @@ public void listCertificates() throws Exception { } } - PagedList listResult = keyVaultClient.listCertificates(getVaultUri(), PAGELIST_MAX_CERTS).getBody(); + PagedList listResult = keyVaultClient.listCertificates(getVaultUri(), PAGELIST_MAX_CERTS); Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().getItems().size()); HashSet toDelete = new HashSet(); @@ -716,7 +716,7 @@ public void listCertificateVersions() throws Exception { .Builder(getVaultUri(), certificateName, certificateContent) .withPassword(certificatePassword) .withPolicy(certificatePolicy) - .build()).getBody(); + .build()); CertificateIdentifier id = certificateBundle.certificateIdentifier(); certificates.add(id.identifier()); break; @@ -732,10 +732,10 @@ public void listCertificateVersions() throws Exception { } } - PagedList listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName, PAGELIST_MAX_CERTS).getBody(); + PagedList listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName, PAGELIST_MAX_CERTS); Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName).getBody(); + listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName); for (CertificateItem item : listResult) { if(item != null) { @@ -781,13 +781,13 @@ public void issuerCrudOperations() throws Exception { .Builder(getVaultUri(), "issuer1", certificateIssuer.provider()) .withCredentials(certificateIssuer.credentials()) .withOrganizationDetails(certificateIssuer.organizationDetails()) - .build()).getBody(); + .build()); validateCertificateIssuer(certificateIssuer, createdCertificateIssuer); String certificateIssuerName = createdCertificateIssuer.issuerIdentifier().name(); IssuerBundle retrievedCertificateIssuer = keyVaultClient.getCertificateIssuer(getVaultUri(), - certificateIssuerName).getBody(); + certificateIssuerName); validateCertificateIssuer(certificateIssuer, retrievedCertificateIssuer); @@ -803,13 +803,13 @@ public void issuerCrudOperations() throws Exception { .withCredentials(updatedCredentials) .withOrganizationDetails(retrievedCertificateIssuer.organizationDetails()) .withAttributes(retrievedCertificateIssuer.attributes()) - .build()).getBody(); + .build()); validateCertificateIssuer(retrievedCertificateIssuer, updatedCertificateIssuer); Assert.assertNotNull(updatedCertificateIssuer.organizationDetails()); - IssuerBundle deletedCertificateIssuer = keyVaultClient.deleteCertificateIssuer(getVaultUri(), certificateIssuerName).getBody(); + IssuerBundle deletedCertificateIssuer = keyVaultClient.deleteCertificateIssuer(getVaultUri(), certificateIssuerName); validateCertificateIssuer(updatedCertificateIssuer, deletedCertificateIssuer); @@ -844,7 +844,7 @@ public void contactsCrudOperations() throws Exception { Contacts certificateContacts = new Contacts(); certificateContacts.withContactList(contacts); - Contacts createdCertificateContacts = keyVaultClient.setCertificateContacts(getVaultUri(), certificateContacts).getBody(); + Contacts createdCertificateContacts = keyVaultClient.setCertificateContacts(getVaultUri(), certificateContacts); Assert.assertNotNull(createdCertificateContacts); Assert.assertNotNull(createdCertificateContacts.contactList()); Assert.assertTrue(createdCertificateContacts.contactList().size() == 2); @@ -857,20 +857,20 @@ public void contactsCrudOperations() throws Exception { Assert.assertTrue(createContacts[1].phone().equalsIgnoreCase("8888888888")); // Get - Contacts retrievedCertificateContacts = keyVaultClient.getCertificateContacts(getVaultUri()).getBody(); + Contacts retrievedCertificateContacts = keyVaultClient.getCertificateContacts(getVaultUri()); Assert.assertNotNull(retrievedCertificateContacts); Assert.assertNotNull(retrievedCertificateContacts.contactList()); Assert.assertTrue(retrievedCertificateContacts.contactList().size() == 2); // Delete - Contacts deletedCertificateContacts = keyVaultClient.deleteCertificateContacts(getVaultUri()).getBody(); + Contacts deletedCertificateContacts = keyVaultClient.deleteCertificateContacts(getVaultUri()); Assert.assertNotNull(deletedCertificateContacts); Assert.assertNotNull(deletedCertificateContacts.contactList()); Assert.assertTrue(deletedCertificateContacts.contactList().size() == 2); // Get after delete try { - keyVaultClient.getCertificateContacts(getVaultUri()).getBody(); + keyVaultClient.getCertificateContacts(getVaultUri()); } catch (KeyVaultErrorException e) { Assert.assertNotNull(e.getBody().error()); Assert.assertEquals("ContactsNotFound", e.getBody().error().code()); @@ -890,7 +890,7 @@ private static CertificateBundle pollOnCertificateOperation(CertificateOperation while (pendingPollCount < 21) { String certificateName = certificateOperation.certificateOperationIdentifier().name(); CertificateOperation pendingCertificateOperation = keyVaultClient - .getCertificateOperation(getVaultUri(), certificateName).getBody(); + .getCertificateOperation(getVaultUri(), certificateName); if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)) { Thread.sleep(10000); pendingPollCount += 1; @@ -898,7 +898,7 @@ private static CertificateBundle pollOnCertificateOperation(CertificateOperation } if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_COMPLETED)) { - return keyVaultClient.getCertificate(pendingCertificateOperation.target()).getBody(); + return keyVaultClient.getCertificate(pendingCertificateOperation.target()); } throw new Exception(String.format( @@ -1100,7 +1100,7 @@ private void validatePem(CertificateBundle certificateBundle, String subjectName // Retrieve the secret backing the certificate SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); - SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()).getBody(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()); Assert.assertTrue(secret.managed()); String secretValue = secret.value(); diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java index 92de113eb9f98..863b2f8a4166a 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -68,7 +68,7 @@ public void transparentAuthentication() throws Exception { .withKeyOperations(keyOps) .withKeySize(2048) .withTags(tags) - .build()).getBody(); + .build()); validateRsaKeyBundle(bundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, keyOps, attribute); } @@ -76,7 +76,7 @@ public void transparentAuthentication() throws Exception { // Create a key on a different vault. Key Vault Data Plane returns 401, // which must be transparently handled by KeyVaultCredentials. { - KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()).getBody(); + KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } @@ -112,7 +112,7 @@ private void checkImportOperation(KeyBundle keyBundle, boolean importToHardware) .withHsm(importToHardware) .withAttributes(attribute) .withTags(tags) - .build()).getBody(); + .build()); validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? JsonWebKeyType.RSA_HSM : JsonWebKeyType.RSA, importedJwk.keyOps(), attribute); checkEncryptDecryptSequence(importedJwk, importResultBundle); @@ -127,7 +127,7 @@ private void checkEncryptDecryptSequence(JsonWebKey importedKey, KeyBundle impor // Encrypt in the service. { - KeyOperationResult result = keyVaultClient.encrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); + KeyOperationResult result = keyVaultClient.encrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); } @@ -152,7 +152,7 @@ private void checkEncryptDecryptSequence(JsonWebKey importedKey, KeyBundle impor // Decrypt in the service. { - KeyOperationResult result = keyVaultClient.decrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA1_5, cipherText).getBody(); + KeyOperationResult result = keyVaultClient.decrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA1_5, cipherText); byte[] beforeEncrypt = plainText; byte[] afterDecrypt = result.result(); @@ -166,7 +166,7 @@ public void crudOperations() throws Exception { KeyBundle createdBundle; { // Create key - createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()).getBody(); + createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } @@ -175,31 +175,31 @@ public void crudOperations() throws Exception { { // Get key using kid WO version - KeyBundle readBundle = keyVaultClient.getKey(keyId.baseIdentifier()).getBody(); + KeyBundle readBundle = keyVaultClient.getKey(keyId.baseIdentifier()); compareKeyBundles(createdBundle, readBundle); } { // Get key using full kid as defined in the bundle - KeyBundle readBundle = keyVaultClient.getKey(createdBundle.key().kid()).getBody(); + KeyBundle readBundle = keyVaultClient.getKey(createdBundle.key().kid()); compareKeyBundles(createdBundle, readBundle); } { // Get key using vault and key name. - KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME).getBody(); + KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME); compareKeyBundles(createdBundle, readBundle); } { // Get key using vault, key name and version. - KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME, keyId.version()).getBody(); + KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME, keyId.version()); compareKeyBundles(createdBundle, readBundle); } { // Get key using vault, key name and a null version. - KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME).getBody(); + KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME); compareKeyBundles(createdBundle, readBundle); } @@ -224,7 +224,7 @@ public void crudOperations() throws Exception { .withKeyOperations(key_ops) .withAttributes(createdBundle.attributes()) .withTags(createdBundle.tags()) - .build()).getBody(); + .build()); compareKeyBundles(createdBundle, updatedBundle); @@ -253,14 +253,14 @@ public void crudOperations() throws Exception { .withKeyOperations(key_ops) .withAttributes(createdBundle.attributes()) .withTags(createdBundle.tags()) - .build()).getBody(); + .build()); compareKeyBundles(createdBundle, updatedBundle); } { // Delete key - KeyBundle deleteBundle = keyVaultClient.deleteKey(getVaultUri(), KEY_NAME).getBody(); + KeyBundle deleteBundle = keyVaultClient.deleteKey(getVaultUri(), KEY_NAME); compareKeyBundles(createdBundle, deleteBundle); } @@ -285,14 +285,14 @@ public void backupRestore() throws Exception { { createdBundle = keyVaultClient.createKey( new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA) - .build()).getBody(); + .build()); validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } // Creates a backup of key. byte[] keyBackup; { - keyBackup = keyVaultClient.backupKey(getVaultUri(), KEY_NAME).getBody().value(); + keyBackup = keyVaultClient.backupKey(getVaultUri(), KEY_NAME).value(); } // Deletes the key. @@ -302,7 +302,7 @@ public void backupRestore() throws Exception { // Restores the key. { - KeyBundle restoredBundle = keyVaultClient.restoreKey(getVaultUri(), keyBackup).getBody(); + KeyBundle restoredBundle = keyVaultClient.restoreKey(getVaultUri(), keyBackup); compareKeyBundles(createdBundle, restoredBundle); } @@ -316,7 +316,7 @@ public void listKeys() throws Exception { int failureCount = 0; for (;;) { try { - KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME + i, JsonWebKeyType.RSA).build()).getBody(); + KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME + i, JsonWebKeyType.RSA).build()); KeyIdentifier kid = new KeyIdentifier(createdBundle.key().kid()); keys.add(kid.baseIdentifier()); break; @@ -332,7 +332,7 @@ public void listKeys() throws Exception { } } - PagedList listResult = keyVaultClient.listKeys(getVaultUri(), PAGELIST_MAX_KEYS).getBody(); + PagedList listResult = keyVaultClient.listKeys(getVaultUri(), PAGELIST_MAX_KEYS); Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().getItems().size()); HashSet toDelete = new HashSet(); @@ -367,7 +367,7 @@ public void listKeyVersions() throws Exception { int failureCount = 0; for (;;) { try { - KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()).getBody(); + KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); keys.add(createdBundle.key().kid()); break; } catch (KeyVaultErrorException e) { @@ -382,10 +382,10 @@ public void listKeyVersions() throws Exception { } } - PagedList listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME, MAX_KEYS).getBody(); + PagedList listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME, MAX_KEYS); //TODO bug: Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME).getBody(); + listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME); for (KeyItem item : listResult) { if(item != null) { @@ -413,19 +413,19 @@ public void encryptDecryptOperations() throws Exception { // encrypt and decrypt using kid WO version { - result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); + result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); - result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); + result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); Assert.assertArrayEquals(plainText, result.result()); } // encrypt and decrypt using full kid { - result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); + result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); - result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); + result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); Assert.assertArrayEquals(plainText, result.result()); } } @@ -445,19 +445,19 @@ public void wrapUnwrapOperations() throws Exception { // wrap and unwrap using kid WO version { - result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); - result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); + result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); Assert.assertArrayEquals(plainText, result.result()); } // wrap and unwrap using full kid { - result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); - result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText).getBody(); + result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); Assert.assertArrayEquals(plainText, result.result()); } } @@ -481,19 +481,19 @@ public void signVerifyOperations() throws Exception { // Using kid WO version { - result = keyVaultClient.sign(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest).getBody(); + result = keyVaultClient.sign(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest); signature = result.result(); - verifyResult = keyVaultClient.verify(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest, signature).getBody(); + verifyResult = keyVaultClient.verify(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest, signature); Assert.assertEquals(new Boolean(true), verifyResult.value()); } // Using full kid { - result = keyVaultClient.sign(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest).getBody(); + result = keyVaultClient.sign(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest); signature = result.result(); - verifyResult = keyVaultClient.verify(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signature).getBody(); + verifyResult = keyVaultClient.verify(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signature); Assert.assertEquals(new Boolean(true), verifyResult.value()); } @@ -511,7 +511,7 @@ private static JsonWebKey importTestKey() throws Exception { new ImportKeyRequest .Builder(getVaultUri(), KEY_NAME, key) .withHsm(false) - .build()).getBody(); + .build()); validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); diff --git a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java index ed6282decdf41..08e6cd13de44e 100755 --- a/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java @@ -49,7 +49,7 @@ public void transparentAuthentication() throws Exception { .withAttributes(attributes) .withContentType(contentType) .withTags(tags) - .build()).getBody(); + .build()); validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, contentType, attributes); } @@ -57,7 +57,7 @@ public void transparentAuthentication() throws Exception { // 401, which must be transparently handled by KeyVaultCredentials. { SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); + new SetSecretRequest.Builder(getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE).build()); validateSecret(secret, getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); } @@ -70,7 +70,7 @@ public void crudOperations() throws Exception { { // Create secret secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()); validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); } @@ -79,25 +79,25 @@ public void crudOperations() throws Exception { { // Get secret using kid WO version - SecretBundle readBundle = keyVaultClient.getSecret(secretId.baseIdentifier()).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(secretId.baseIdentifier()); compareSecrets(secret, readBundle); } { // Get secret using full kid as defined in the bundle - SecretBundle readBundle = keyVaultClient.getSecret(secret.id()).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(secret.id()); compareSecrets(secret, readBundle); } { // Get secret using vault and secret name. - SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME); compareSecrets(secret, readBundle); } { // Get secret using vault, secret name and version. - SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME, secretId.version()).getBody(); + SecretBundle readBundle = keyVaultClient.getSecret(getVaultUri(), SECRET_NAME, secretId.version()); compareSecrets(secret, readBundle); } @@ -119,7 +119,7 @@ public void crudOperations() throws Exception { .withContentType(secret.contentType()) .withAttributes(secret.attributes()) .withTags(secret.tags()) - .build()).getBody(); + .build()); compareSecrets(secret, updatedSecret); // Subsequent operations must use the updated bundle for comparison. @@ -146,7 +146,7 @@ public void crudOperations() throws Exception { .withContentType(secret.contentType()) .withAttributes(secret.attributes()) .withTags(secret.tags()) - .build()).getBody(); + .build()); compareSecrets(secret, updatedSecret); validateSecret(updatedSecret, @@ -157,7 +157,7 @@ public void crudOperations() throws Exception { { // Delete secret - SecretBundle deleteBundle = keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME).getBody(); + SecretBundle deleteBundle = keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME); compareSecrets(secret, deleteBundle); } @@ -181,7 +181,7 @@ public void listSecrets() throws Exception { for (;;) { try { SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME + i, SECRET_VALUE).build()).getBody(); + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME + i, SECRET_VALUE).build()); SecretIdentifier id = new SecretIdentifier(secret.id()); secrets.add(id.baseIdentifier()); break; @@ -197,7 +197,7 @@ public void listSecrets() throws Exception { } } - PagedList listResult = keyVaultClient.listSecrets(getVaultUri(), PAGELIST_MAX_SECRETS).getBody(); + PagedList listResult = keyVaultClient.listSecrets(getVaultUri(), PAGELIST_MAX_SECRETS); Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().getItems().size()); HashSet toDelete = new HashSet(); @@ -233,7 +233,7 @@ public void listSecretVersions() throws Exception { for (;;) { try { SecretBundle secret = keyVaultClient.setSecret( - new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()).getBody(); + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()); secrets.add(secret.id()); break; } catch (KeyVaultErrorException e) { @@ -248,10 +248,10 @@ public void listSecretVersions() throws Exception { } } - PagedList listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME, PAGELIST_MAX_SECRETS).getBody(); + PagedList listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME, PAGELIST_MAX_SECRETS); Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME).getBody(); + listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME); for (SecretItem item : listResult) { if(item != null) { secrets.remove(item.id());