Search in sources :

Example 6 with KeyBundle

use of com.microsoft.azure.keyvault.models.KeyBundle in project azure-sdk-for-java by Azure.

the class KeyVaultClientImpl method updateKeyWithServiceResponseAsync.

/**
     * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission.
     *
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param keyName The name of key to update.
     * @param keyVersion The version of the key to update.
     * @return the observable to the KeyBundle object
     */
public Observable<ServiceResponse<KeyBundle>> updateKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion) {
    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<JsonWebKeyOperation> keyOps = null;
    final KeyAttributes keyAttributes = null;
    final Map<String, String> tags = null;
    KeyUpdateParameters parameters = new KeyUpdateParameters();
    parameters.withKeyOps(null);
    parameters.withKeyAttributes(null);
    parameters.withTags(null);
    String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
    return service.updateKey(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<KeyBundle>>>() {

        @Override
        public Observable<ServiceResponse<KeyBundle>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<KeyBundle> clientResponse = updateKeyDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : KeyAttributes(com.microsoft.azure.keyvault.models.KeyAttributes) KeyUpdateParameters(com.microsoft.azure.keyvault.models.KeyUpdateParameters) Observable(rx.Observable) ResponseBody(okhttp3.ResponseBody) Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) ServiceResponse(com.microsoft.rest.ServiceResponse) JsonWebKeyOperation(com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle)

Example 7 with KeyBundle

use of com.microsoft.azure.keyvault.models.KeyBundle in project azure-sdk-for-java by Azure.

the class CertificateOperationsTest method createSelfSignedCertificatePkcs12.

/**
     * 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"
    IssuerParameters issuerParameters = new IssuerParameters().withName(ISSUER_SELF);
    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties).withIssuerParameters(issuerParameters).withX509CertificateProperties(x509Properties);
    Attributes attribute = new CertificateAttributes().withEnabled(true).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);
    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());
    Assert.assertTrue(secret.managed());
    // Retrieve the key backing the certificate
    KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier();
    KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier());
    Assert.assertTrue(keyBundle.managed());
    // 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);
    Assert.assertNotNull(deletedCertificateBundle);
    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}
Also used : KeyIdentifier(com.microsoft.azure.keyvault.KeyIdentifier) CertificateAttributes(com.microsoft.azure.keyvault.models.CertificateAttributes) CertificateBundle(com.microsoft.azure.keyvault.models.CertificateBundle) KeyVaultErrorException(com.microsoft.azure.keyvault.models.KeyVaultErrorException) IssuerParameters(com.microsoft.azure.keyvault.models.IssuerParameters) CertificatePolicy(com.microsoft.azure.keyvault.models.CertificatePolicy) Attributes(com.microsoft.azure.keyvault.models.Attributes) CertificateAttributes(com.microsoft.azure.keyvault.models.CertificateAttributes) X509CertificateProperties(com.microsoft.azure.keyvault.models.X509CertificateProperties) CertificateOperation(com.microsoft.azure.keyvault.models.CertificateOperation) KeyStore(java.security.KeyStore) DateTime(org.joda.time.DateTime) X509Certificate(java.security.cert.X509Certificate) CreateCertificateRequest(com.microsoft.azure.keyvault.requests.CreateCertificateRequest) SecretIdentifier(com.microsoft.azure.keyvault.SecretIdentifier) SecretBundle(com.microsoft.azure.keyvault.models.SecretBundle) SecretProperties(com.microsoft.azure.keyvault.models.SecretProperties) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle) Test(org.junit.Test)

Example 8 with KeyBundle

use of com.microsoft.azure.keyvault.models.KeyBundle in project azure-sdk-for-java by Azure.

the class AsyncOperationsTest method keyAsync.

@Test
public void keyAsync() throws Exception {
    String vault = getVaultUri();
    String keyname = "mykey";
    CreateKeyRequest createKeyRequest = new CreateKeyRequest.Builder(vault, keyname, JsonWebKeyType.RSA).build();
    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();
    Assert.assertNotNull(keyBundle);
    keyBundle = keyVaultClient.getKeyAsync(keyBundle.key().kid(), null).get();
    Assert.assertNotNull(keyBundle);
    List<KeyItem> keyItems = keyVaultClient.listKeysAsync(vault, 2, null).get();
    Assert.assertNotNull(keyItems);
    List<KeyItem> keyVersionItems = keyVaultClient.listKeyVersionsAsync(getVaultUri(), keyname, 2, null).get();
    Assert.assertNotNull(keyVersionItems);
    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();
    Assert.assertNotNull(restoreResult);
    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();
    Assert.assertNotNull(decryptResult);
    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();
    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();
    Assert.assertNotNull(signResult);
    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();
    Assert.assertNotNull(keyBundle);
    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).body().error().code());
        } else
            throw ex;
    }
}
Also used : KeyVaultErrorException(com.microsoft.azure.keyvault.models.KeyVaultErrorException) KeyOperationResult(com.microsoft.azure.keyvault.models.KeyOperationResult) KeyItem(com.microsoft.azure.keyvault.models.KeyItem) BackupKeyResult(com.microsoft.azure.keyvault.models.BackupKeyResult) UpdateKeyRequest(com.microsoft.azure.keyvault.requests.UpdateKeyRequest) Random(java.util.Random) KeyVerifyResult(com.microsoft.azure.keyvault.models.KeyVerifyResult) CreateKeyRequest(com.microsoft.azure.keyvault.requests.CreateKeyRequest) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle) MessageDigest(java.security.MessageDigest) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 9 with KeyBundle

use of com.microsoft.azure.keyvault.models.KeyBundle in project azure-sdk-for-java by Azure.

the class KeyVaultClientImpl method createKeyWithServiceResponseAsync.

/**
     * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission.
     *
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param keyName The name for the new key. The system will generate the version name for the new key.
     * @param kty The type of key to create. For 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. For example, 1024 or 2048.
     * @param keyOps the List&lt;JsonWebKeyOperation&gt; 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<ServiceResponse<KeyBundle>> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List<JsonWebKeyOperation> keyOps, KeyAttributes keyAttributes, Map<String, String> tags) {
    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);
    return service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<KeyBundle>>>() {

        @Override
        public Observable<ServiceResponse<KeyBundle>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<KeyBundle> clientResponse = createKeyDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) ServiceResponse(com.microsoft.rest.ServiceResponse) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle) KeyCreateParameters(com.microsoft.azure.keyvault.models.KeyCreateParameters) Observable(rx.Observable) ResponseBody(okhttp3.ResponseBody)

Example 10 with KeyBundle

use of com.microsoft.azure.keyvault.models.KeyBundle in project azure-sdk-for-java by Azure.

the class KeyVaultClientImpl method restoreKeyWithServiceResponseAsync.

/**
     * Restores a backed up key to a vault.
     *
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param keyBundleBackup The backup blob associated with a key bundle.
     * @return the observable to the KeyBundle object
     */
public Observable<ServiceResponse<KeyBundle>> restoreKeyWithServiceResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup) {
    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);
    return service.restoreKey(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<KeyBundle>>>() {

        @Override
        public Observable<ServiceResponse<KeyBundle>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<KeyBundle> clientResponse = restoreKeyDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) KeyRestoreParameters(com.microsoft.azure.keyvault.models.KeyRestoreParameters) ServiceResponse(com.microsoft.rest.ServiceResponse) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle) Observable(rx.Observable) ResponseBody(okhttp3.ResponseBody)

Aggregations

KeyBundle (com.microsoft.azure.keyvault.models.KeyBundle)18 Test (org.junit.Test)9 ServiceResponse (com.microsoft.rest.ServiceResponse)7 ResponseBody (okhttp3.ResponseBody)7 Response (retrofit2.Response)7 Observable (rx.Observable)7 KeyVaultErrorException (com.microsoft.azure.keyvault.models.KeyVaultErrorException)5 KeyAttributes (com.microsoft.azure.keyvault.models.KeyAttributes)4 KeyIdentifier (com.microsoft.azure.keyvault.KeyIdentifier)3 KeyItem (com.microsoft.azure.keyvault.models.KeyItem)3 CreateKeyRequest (com.microsoft.azure.keyvault.requests.CreateKeyRequest)3 JsonWebKey (com.microsoft.azure.keyvault.webkey.JsonWebKey)3 ExecutionException (java.util.concurrent.ExecutionException)3 DateTime (org.joda.time.DateTime)3 IKey (com.microsoft.azure.keyvault.core.IKey)2 KeyVaultKeyResolver (com.microsoft.azure.keyvault.extensions.KeyVaultKeyResolver)2 Attributes (com.microsoft.azure.keyvault.models.Attributes)2 KeyCreateParameters (com.microsoft.azure.keyvault.models.KeyCreateParameters)2 KeyImportParameters (com.microsoft.azure.keyvault.models.KeyImportParameters)2 KeyUpdateParameters (com.microsoft.azure.keyvault.models.KeyUpdateParameters)2