com.microsoft.azure.keyvault.models.KeyBundle Java Examples

The following examples show how to use com.microsoft.azure.keyvault.models.KeyBundle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyOperationsTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private void checkImportOperation(KeyBundle keyBundle, boolean importToHardware) throws Exception {
    Attributes attribute = new KeyAttributes()
            .withEnabled(true)
            .withExpires(new DateTime().withYear(2050).withMonthOfYear(1))
            .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1));
    
    Map<String, String> tags = new HashMap<String, String>();
    tags.put("foo", "baz");
    
    JsonWebKey importedJwk = keyBundle.key();
    KeyBundle importResultBundle = keyVaultClient.importKey(
            new ImportKeyRequest
                .Builder(getVaultUri(), KEY_NAME, keyBundle.key())
                    .withHsm(importToHardware)
                    .withAttributes(attribute)
                    .withTags(tags)
                    .build());
    
    validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? JsonWebKeyType.RSA_HSM : JsonWebKeyType.RSA, importedJwk.keyOps(), attribute);
    checkEncryptDecryptSequence(importedJwk, importResultBundle);
    Assert.assertTrue(importResultBundle.key().isValid());
}
 
Example #2
Source File: KeyOperationsTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static JsonWebKey importTestKey() throws Exception {

        KeyBundle keyBundle = new KeyBundle();
        JsonWebKey key = JsonWebKey.fromRSA(getTestKeyMaterial());

        key.withKty(JsonWebKeyType.RSA);
        key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT, JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY, JsonWebKeyOperation.WRAP_KEY, JsonWebKeyOperation.UNWRAP_KEY));

        keyBundle = keyVaultClient.importKey(
                new ImportKeyRequest
                    .Builder(getVaultUri(), KEY_NAME, key)
                        .withHsm(false)
                        .build());
        
        validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null);

        return keyBundle.key();
    }
 
Example #3
Source File: KeyImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<Key> updateResourceAsync() {
    Observable<Key> set = Observable.just((Key) this);
    if (createKeyRequest != null || importKeyRequest != null) {
        set = createResourceAsync();
    }
    return set.flatMap(new Func1<Key, Observable<KeyBundle>>() {
        @Override
        public Observable<KeyBundle> call(Key secret) {
            return Observable.from(vault.client().updateKeyAsync(updateKeyRequest.build(), null));
        }
    }).flatMap(new Func1<KeyBundle, Observable<Key>>() {
        @Override
        public Observable<Key> call(KeyBundle secretBundle) {
            return refreshAsync();
        }
    }).doOnCompleted(new Action0() {
        @Override
        public void call() {
            createKeyRequest = null;
            importKeyRequest = null;
            updateKeyRequest = new UpdateKeyRequest.Builder(vault.vaultUri(), name());
        }
    });
}
 
Example #4
Source File: KeyImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public PagedList<Key> listVersions() {
    return new PagedListConverter<KeyItem, Key>() {

        @Override
        public Observable<Key> typeConvertAsync(final KeyItem keyItem) {
            return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {

                @Override
                protected ServiceFuture<KeyBundle> callAsync() {
                    return vault.client().getKeyAsync(keyItem.identifier().identifier(), null);
                }

                @Override
                protected Key wrapModel(KeyBundle keyBundle) {
                    return new KeyImpl(keyBundle.keyIdentifier().name(), keyBundle, vault);
                }
            }.toObservable();
        }
    }.convert(vault.client().listKeyVersions(vault.vaultUri(), name()));
}
 
Example #5
Source File: KeyOperationsTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static void validateRsaKeyBundle(KeyBundle bundle, String vault, String keyName, JsonWebKeyType kty, List<JsonWebKeyOperation> key_ops, Attributes attributes) throws Exception {
    String prefix = vault + "/keys/" + keyName + "/";
    String kid = bundle.key().kid();
    Assert.assertTrue( 
            String.format("\"kid\" should start with \"%s\", but instead the value is \"%s\".", prefix, kid), 
            kid.startsWith(prefix));
    Assert.assertEquals(kty, bundle.key().kty());
    Assert.assertNotNull("\"n\" should not be null.", bundle.key().n());
    Assert.assertNotNull("\"e\" should not be null.", bundle.key().e());
    if (key_ops != null) {
        Assert.assertTrue(key_ops.equals(bundle.key().keyOps()));
    }
    Assert.assertNotNull("\"created\" should not be null.", bundle.attributes().created());
    Assert.assertNotNull("\"updated\" should not be null.", bundle.attributes().updated());
            
    Assert.assertTrue(bundle.managed() == null || bundle.managed() == false);
    Assert.assertTrue(bundle.key().isValid());
}
 
Example #6
Source File: KeyImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Key> listVersionsAsync() {
    return new KeyVaultFutures.ListCallbackObserver<KeyItem, KeyIdentifier>() {

        @Override
        protected void list(ListOperationCallback<KeyItem> callback) {
            vault.client().listKeyVersionsAsync(vault.vaultUri(), name(), callback);
        }

        @Override
        protected Observable<KeyIdentifier> typeConvertAsync(KeyItem o) {
            return Observable.just(o.identifier());
        }
    }.toObservable()
            .flatMap(new Func1<KeyIdentifier, Observable<Key>>() {
                @Override
                public Observable<Key> call(final KeyIdentifier keyIdentifier) {
                    return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {

                        @Override
                        protected ServiceFuture<KeyBundle> callAsync() {
                            return vault.client().getKeyAsync(keyIdentifier.identifier(), null);
                        }

                        @Override
                        protected Key wrapModel(KeyBundle keyBundle) {
                            return new KeyImpl(keyIdentifier.name(), keyBundle, vault);
                        }
                    }.toObservable();
                }
            });
}
 
Example #7
Source File: KeyOperationsTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Test
public void backupRestoreForKeyOperationsTest() throws Exception {

    KeyBundle createdBundle;

    // Creates a key
    {
        createdBundle = keyVaultClient.createKey(
                new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA)
                                    .build());
        validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null);
    }

    // Creates a backup of key.
    byte[] keyBackup;
    {
        keyBackup = keyVaultClient.backupKey(getVaultUri(), KEY_NAME).value();
        if (isRecordMode()) {
        	Thread.sleep(20000);
        }
    }

    // Deletes the key.
    {
        keyVaultClient.deleteKey(getVaultUri(), KEY_NAME);
        pollOnKeyDeletion(getVaultUri(), KEY_NAME);
    }
    
    keyVaultClient.purgeDeletedKey(getVaultUri(), KEY_NAME);
    if (isRecordMode()) {
    	Thread.sleep(40000);
    }

    // Restores the key.
    {
        KeyBundle restoredBundle = keyVaultClient.restoreKey(getVaultUri(), keyBackup);
        compareKeyBundles(createdBundle, restoredBundle);
    }
    
}
 
Example #8
Source File: KeyVaultKeyResolverBCProviderTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Test
public void KeyVault_KeyVaultKeyResolver_Key_KeyVaultKeyResolverBCProviderTest() throws InterruptedException, ExecutionException
{
	String TEST_KEY_NAME = KEY_NAME + "1";
    try {
        // Create a key on a vault.
        CreateKeyRequest           request  = new CreateKeyRequest.Builder(getVaultUri(), TEST_KEY_NAME, JsonWebKeyType.RSA).build();
        KeyBundle bundle = keyVaultClient.createKey(request);

        if ( bundle != null )
        {
            try
            {
                // ctor with client
                KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient, _provider );

                Future<IKey> baseKeyFuture    = resolver.resolveKeyAsync( bundle.keyIdentifier().baseIdentifier() );
                Future<IKey> versionKeyFuture = resolver.resolveKeyAsync( bundle.keyIdentifier().identifier() );

                IKey baseKey    = baseKeyFuture.get();
                IKey versionKey = versionKeyFuture.get();

                Assert.assertEquals( baseKey.getKid(), versionKey.getKid() );
            }
            finally
            {
                // Delete the key
                keyVaultClient.deleteKey( getVaultUri(), TEST_KEY_NAME );
                pollOnKeyDeletion( getVaultUri(), TEST_KEY_NAME );
                keyVaultClient.purgeDeletedKey( getVaultUri(), TEST_KEY_NAME);

            }
        }
    }
    catch ( Exception ex )
    {
        Assert.fail(ex.getMessage());
    }
}
 
Example #9
Source File: KeyVaultKeyResolverDefaultProviderTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Test
public void KeyVault_KeyVaultKeyResolver_Key_KeyVaultKeyResolverDefaultProviderTest() throws InterruptedException, ExecutionException
{
	String TEST_KEY_NAME = KEY_NAME + "1";
    try {
        // Create a key on a vault.
        CreateKeyRequest  request   = new CreateKeyRequest.Builder(getVaultUri(), TEST_KEY_NAME, JsonWebKeyType.RSA).build();
        KeyBundle         keyBundle = keyVaultClient.createKey(request);
        
        try
        {
            // ctor with client
            final KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient );

            IKey baseKey    = resolver.resolveKeyAsync( keyBundle.keyIdentifier().baseIdentifier() ).get();
            IKey versionKey = resolver.resolveKeyAsync( keyBundle.keyIdentifier().identifier() ).get();
                                    
            Assert.assertEquals( baseKey.getKid(), versionKey.getKid() );
        }
        finally
        {
            // Delete the key
            keyVaultClient.deleteKey( getVaultUri(), TEST_KEY_NAME );
            pollOnKeyDeletion( getVaultUri(), TEST_KEY_NAME );
            keyVaultClient.purgeDeletedKey( getVaultUri(), TEST_KEY_NAME );
        }
    } catch(Exception ex) {
        fail(ex.getMessage());
    }
}
 
Example #10
Source File: KeyVaultClientCustomImpl.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Override
public Observable<ServiceResponse<KeyBundle>> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName,
        JsonWebKeyType kty, Integer keySize, List<JsonWebKeyOperation> keyOps, KeyAttributes keyAttributes,
        Map<String, String> tags) {
    return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags,
            null);
}
 
Example #11
Source File: KeyVaultKeyResolver.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Override
public IKey apply(KeyBundle keyBundle) {

    if (keyBundle != null) {
        return new KeyVaultKey(client, keyBundle);
    }

    return null;
}
 
Example #12
Source File: KeyVaultKey.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
protected KeyVaultKey(KeyVaultClient client, KeyBundle keyBundle) {

        if (client == null) {
            throw new IllegalArgumentException("client");
        }

        if (keyBundle == null) {
            throw new IllegalArgumentException("keyBundle");
        }

        JsonWebKey key = keyBundle.key();

        if (key == null) {
            throw new IllegalArgumentException("keyBundle must contain a key");
        }

        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.RSA_HSM)) {
            // The private key is not available for KeyVault keys
            implementation = new RsaKey(key.kid(), key.toRSA(false));
        }

        if (implementation == null) {
            throw new IllegalArgumentException(String.format("The key type %s is not supported", key.kty()));
        }

        this.client = client;
    }
 
Example #13
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Key> getByNameAsync(final String name) {
    return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {

        @Override
        ServiceFuture<KeyBundle> callAsync() {
            return inner.getKeyAsync(vault.vaultUri(), name, null);
        }

        @Override
        Key wrapModel(KeyBundle keyBundle) {
            return KeysImpl.this.wrapModel(keyBundle);
        }
    }.toObservable();
}
 
Example #14
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Key> restoreAsync(final byte[] backup) {
    return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {
        @Override
        protected ServiceFuture<KeyBundle> callAsync() {
            return vault.client().restoreKeyAsync(vault.vaultUri(), backup, null);
        }

        @Override
        protected Key wrapModel(KeyBundle keyBundle) {
            return KeysImpl.this.wrapModel(keyBundle);
        }
    }.toObservable();
}
 
Example #15
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Key> getByNameAndVersionAsync(final String name, final String version) {
    return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {

        @Override
        ServiceFuture<KeyBundle> callAsync() {
            return inner.getKeyAsync(vault.vaultUri(), name, version, null);
        }

        @Override
        Key wrapModel(KeyBundle keyBundle) {
            return KeysImpl.this.wrapModel(keyBundle);
        }
    }.toObservable();
}
 
Example #16
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
protected KeyImpl wrapModel(KeyBundle inner) {
    if (inner == null) {
        return null;
    }
    return new KeyImpl(inner.keyIdentifier().name(), inner, vault);
}
 
Example #17
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public ServiceFuture<Key> getByIdAsync(final String id, final ServiceCallback<Key> callback) {
    return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {
        @Override
        protected ServiceFuture<KeyBundle> callAsync() {
            return inner.getKeyAsync(id, null);
        }

        @Override
        protected Key wrapModel(KeyBundle keyBundle) {
            return KeysImpl.this.wrapModel(keyBundle);
        }
    }.toFuture(callback);
}
 
Example #18
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Key> call(final KeyItem keyItem) {
    return new KeyVaultFutures.ServiceFutureConverter<KeyBundle, Key>() {

        @Override
        protected ServiceFuture<KeyBundle> callAsync() {
            return vault.client().getKeyAsync(keyItem.identifier().identifier(), null);
        }

        @Override
        protected Key wrapModel(KeyBundle keyBundle) {
            return KeysImpl.this.wrapModel(keyBundle);
        }
    }.toObservable();
}
 
Example #19
Source File: KeyVaultClientCustomImpl.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Override
public KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize,
        List<JsonWebKeyOperation> keyOps, KeyAttributes keyAttributes, Map<String, String> tags) {
    return createKey(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags, null);
}
 
Example #20
Source File: KeyVaultClientCustomImpl.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Override
public Observable<KeyBundle> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty,
        Integer keySize, List<JsonWebKeyOperation> keyOps, KeyAttributes keyAttributes, Map<String, String> tags) {
    return createKeyAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags,
            (JsonWebKeyCurveName) null);
}
 
Example #21
Source File: KeyVaultClientCustomImpl.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Override
public ServiceFuture<KeyBundle> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty,
        Integer keySize, List<JsonWebKeyOperation> keyOps, KeyAttributes keyAttributes, Map<String, String> tags,
        ServiceCallback<KeyBundle> serviceCallback) {
    return createKeyAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags, null, serviceCallback);
}
 
Example #22
Source File: AzureKeyVaultScannerTest.java    From clouditor with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void setUpOnce() {
  discoverAssets(
      AzureKeyVaultScanner::new,
      api -> {
        var vault1 = createWithId(Vault.class, "vault-with-expiry", new VaultInner());

        var key =
            createKey(
                "key",
                "key-name",
                new KeyBundle()
                    .withAttributes(
                        (KeyAttributes)
                            new KeyAttributes().withExpires(new DateTime().plusWeeks(30))));

        when(vault1.keys().list()).thenReturn(MockedPagedList.of(key));

        var vault2 = createWithId(Vault.class, "vault-without-expiry", new VaultInner());

        key = createKey("key", "key-name", new KeyBundle());

        when(vault2.keys().list()).thenReturn(MockedPagedList.of(key));

        when(api.azure.vaults().listByResourceGroup(anyString()))
            .thenReturn(MockedPagedList.of(vault1, vault2));

        var settings =
            createDiagnosticsSetting(
                "some-id",
                "some-name",
                new DiagnosticSettingsResourceInner()
                    .withLogs(
                        List.of(
                            new LogSettings()
                                .withEnabled(true)
                                .withRetentionPolicy(
                                    new RetentionPolicy().withEnabled(true).withDays(270)))));

        when(api.monitor().diagnosticSettings().listByResource(anyString()))
            .thenReturn(MockedPagedList.of(settings));
      });
}
 
Example #23
Source File: KeyOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Test
public void listKeyVersionsForKeyOperationsTest() throws Exception {

    HashSet<String> keys = new HashSet<String>();
    for (int i = 0; i < MAX_KEYS; ++i) {
        int failureCount = 0;
        for (;;) {
            try {
                KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build());
                keys.add(createdBundle.key().kid());
                break;
            } catch (KeyVaultErrorException e) {
                ++failureCount;
                if (e.body().error().code().equals("Throttled")) {
                    System.out.println("Waiting to avoid throttling");
                    if (isRecordMode()) {
                    	Thread.sleep(failureCount * 1500);
                    }
                    continue;
                }
                throw e;
            }
        }
    }

    PagedList<KeyItem> 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);
    
    for (KeyItem item : listResult) {
        if(item != null) {
            keys.remove(item.kid());
        }
    }

    Assert.assertEquals(0, keys.size());

    keyVaultClient.deleteKey(getVaultUri(), KEY_NAME);
    pollOnKeyDeletion(getVaultUri(), KEY_NAME);
    
    keyVaultClient.purgeDeletedKey(getVaultUri(), KEY_NAME);
    if (isRecordMode()) {
    	Thread.sleep(40000);        
    }
}
 
Example #24
Source File: KeyOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
private void compareKeyBundles(KeyBundle expected, KeyBundle actual) {
    Assert.assertTrue(expected.key().toString().equals(actual.key().toString()));
    Assert.assertEquals(expected.attributes().enabled(), actual.attributes().enabled());
    if(expected.tags() != null || actual.tags() != null)
        Assert.assertTrue(expected.tags().equals(actual.tags()));
}
 
Example #25
Source File: AsyncOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Test
public void keyAsyncForAsyncOperationsTest() 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(vault, 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();
	pollOnKeyDeletion(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name());
	keyVaultClient.purgeDeletedKey(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name());
	if (isRecordMode()) {
		Thread.sleep(20000);
	}

	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);
	pollOnKeyDeletion(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name());
	keyVaultClient.purgeDeletedKey(keyBundle.keyIdentifier().vault(), keyBundle.keyIdentifier().name());
	if (isRecordMode()) {
		Thread.sleep(20000);
	}
	// 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).body().error().code());
		} else
			throw ex;
	}

}
 
Example #26
Source File: CertificateOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
/**
 * Create a self-signed certificate in PKCS12 format (which includes the
 * private key) certificate.
 * 
 * @throws Exception
 */
@Test
public void createSelfSignedCertificatePkcs12ForCertificateOperationsTest() 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);
    
    pollOnCertificateDeletion(getVaultUri(), certificateName);
    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
    
    keyVaultClient.purgeDeletedCertificate(getVaultUri(), certificateName);
    Thread.sleep(20000);
}
 
Example #27
Source File: AzureScannerTest.java    From clouditor with Apache License 2.0 4 votes vote down vote up
static Key createKey(String id, String name, KeyBundle inner) {
  return createWithIdAndName(Key.class, id, name, inner);
}
 
Example #28
Source File: KeysImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
protected KeyImpl wrapModel(String name) {
    return new KeyImpl(name, new KeyBundle(), vault);
}
 
Example #29
Source File: KeyImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
KeyImpl(String name, KeyBundle innerObject, Vault vault) {
    super(name, innerObject);
    this.vault = vault;
    this.updateKeyRequest = new UpdateKeyRequest.Builder(vault.vaultUri(), name);
}
 
Example #30
Source File: KeyImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
protected Observable<KeyBundle> getInnerAsync() {
    return Observable.from(vault.client().getKeyAsync(id(), null));
}