Search in sources :

Example 1 with KeyIdentifier

use of com.microsoft.azure.keyvault.KeyIdentifier 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 2 with KeyIdentifier

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

the class KeyOperationsTest method crudOperations.

@Test
public void crudOperations() throws Exception {
    KeyBundle createdBundle;
    {
        // Create key
        createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build());
        validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null);
    }
    // Key identifier.
    KeyIdentifier keyId = new KeyIdentifier(createdBundle.key().kid());
    {
        // Get key using kid WO version
        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());
        compareKeyBundles(createdBundle, readBundle);
    }
    {
        // Get key using vault and key name.
        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());
        compareKeyBundles(createdBundle, readBundle);
    }
    {
        // Get key using vault, key name and a null version.
        KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME);
        compareKeyBundles(createdBundle, readBundle);
    }
    {
        // Update key using the kid as defined in the bundle
        // First we create a bundle with the modified attributes.
        createdBundle.attributes().withExpires(new DateTime().withMonthOfYear(2).withDayOfMonth(1).withYear(2050));
        List<JsonWebKeyOperation> key_ops = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT);
        Map<String, String> tags = new HashMap<String, String>();
        tags.put("foo", "baz");
        createdBundle.key().withKeyOps(key_ops);
        createdBundle.withTags(tags);
        // Perform the operation.
        KeyBundle updatedBundle = keyVaultClient.updateKey(new UpdateKeyRequest.Builder(createdBundle.key().kid()).withKeyOperations(key_ops).withAttributes(createdBundle.attributes()).withTags(createdBundle.tags()).build());
        compareKeyBundles(createdBundle, updatedBundle);
        // Subsequent operations must use the updated bundle for comparison.
        createdBundle = updatedBundle;
    }
    {
        // 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));
        List<JsonWebKeyOperation> key_ops = Arrays.asList(JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY);
        createdBundle.key().withKeyOps(key_ops);
        Map<String, String> tags = new HashMap<String, String>();
        tags.put("foo", "baz");
        createdBundle.withTags(tags);
        // Perform the operation.
        KeyBundle updatedBundle = keyVaultClient.updateKey(new UpdateKeyRequest.Builder(getVaultUri(), KEY_NAME).withKeyOperations(key_ops).withAttributes(createdBundle.attributes()).withTags(createdBundle.tags()).build());
        compareKeyBundles(createdBundle, updatedBundle);
    }
    {
        // Delete key
        KeyBundle deleteBundle = keyVaultClient.deleteKey(getVaultUri(), KEY_NAME);
        compareKeyBundles(createdBundle, deleteBundle);
    }
    {
        // Expects a key not found
        try {
            keyVaultClient.getKey(keyId.baseIdentifier());
        } catch (KeyVaultErrorException e) {
            Assert.assertNotNull(e.body().error());
            Assert.assertEquals("KeyNotFound", e.body().error().code());
        }
    }
}
Also used : KeyIdentifier(com.microsoft.azure.keyvault.KeyIdentifier) KeyVaultErrorException(com.microsoft.azure.keyvault.models.KeyVaultErrorException) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle) PagedList(com.microsoft.azure.PagedList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 3 with KeyIdentifier

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

the class KeyOperationsTest method wrapUnwrapOperations.

@Test
public void wrapUnwrapOperations() throws Exception {
    JsonWebKey testKey = importTestKey();
    KeyIdentifier keyId = new KeyIdentifier(testKey.kid());
    // Test variables
    byte[] plainText = new byte[100];
    new Random(0x1234567L).nextBytes(plainText);
    byte[] cipherText;
    KeyOperationResult result;
    // wrap and unwrap using kid WO version
    {
        result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText);
        cipherText = result.result();
        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);
        cipherText = result.result();
        result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText);
        Assert.assertArrayEquals(plainText, result.result());
    }
}
Also used : KeyIdentifier(com.microsoft.azure.keyvault.KeyIdentifier) Random(java.util.Random) KeyOperationResult(com.microsoft.azure.keyvault.models.KeyOperationResult) JsonWebKey(com.microsoft.azure.keyvault.webkey.JsonWebKey) Test(org.junit.Test)

Example 4 with KeyIdentifier

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

the class KeyOperationsTest method listKeys.

@Test
public void listKeys() 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 + i, JsonWebKeyType.RSA).build());
                KeyIdentifier kid = new KeyIdentifier(createdBundle.key().kid());
                keys.add(kid.baseIdentifier());
                break;
            } catch (KeyVaultErrorException e) {
                ++failureCount;
                if (e.body().error().code().equals("Throttled")) {
                    System.out.println("Waiting to avoid throttling");
                    Thread.sleep(failureCount * 1500);
                    continue;
                }
                throw e;
            }
        }
    }
    PagedList<KeyItem> listResult = keyVaultClient.listKeys(getVaultUri(), PAGELIST_MAX_KEYS);
    Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().items().size());
    HashSet<String> toDelete = new HashSet<String>();
    for (KeyItem item : listResult) {
        if (item != null) {
            KeyIdentifier id = new KeyIdentifier(item.kid());
            toDelete.add(id.name());
            keys.remove(item.kid());
        }
    }
    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.body().error().code().equals("Forbidden"))
                throw e;
        }
    }
}
Also used : KeyIdentifier(com.microsoft.azure.keyvault.KeyIdentifier) KeyVaultErrorException(com.microsoft.azure.keyvault.models.KeyVaultErrorException) KeyBundle(com.microsoft.azure.keyvault.models.KeyBundle) KeyItem(com.microsoft.azure.keyvault.models.KeyItem) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with KeyIdentifier

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

the class KeyOperationsTest method signVerifyOperations.

@Test
public void signVerifyOperations() throws Exception {
    JsonWebKey testKey = importTestKey();
    KeyIdentifier keyId = new KeyIdentifier(testKey.kid());
    // Test variables
    byte[] plainText = new byte[100];
    new Random(0x1234567L).nextBytes(plainText);
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(plainText);
    byte[] digest = md.digest();
    byte[] signature;
    KeyOperationResult result;
    KeyVerifyResult verifyResult;
    // Using kid WO version
    {
        result = keyVaultClient.sign(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest);
        signature = result.result();
        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);
        signature = result.result();
        verifyResult = keyVaultClient.verify(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signature);
        Assert.assertEquals(new Boolean(true), verifyResult.value());
    }
}
Also used : KeyIdentifier(com.microsoft.azure.keyvault.KeyIdentifier) Random(java.util.Random) KeyVerifyResult(com.microsoft.azure.keyvault.models.KeyVerifyResult) KeyOperationResult(com.microsoft.azure.keyvault.models.KeyOperationResult) JsonWebKey(com.microsoft.azure.keyvault.webkey.JsonWebKey) MessageDigest(java.security.MessageDigest) Test(org.junit.Test)

Aggregations

KeyIdentifier (com.microsoft.azure.keyvault.KeyIdentifier)6 Test (org.junit.Test)6 KeyBundle (com.microsoft.azure.keyvault.models.KeyBundle)3 KeyOperationResult (com.microsoft.azure.keyvault.models.KeyOperationResult)3 KeyVaultErrorException (com.microsoft.azure.keyvault.models.KeyVaultErrorException)3 JsonWebKey (com.microsoft.azure.keyvault.webkey.JsonWebKey)3 Random (java.util.Random)3 DateTime (org.joda.time.DateTime)2 PagedList (com.microsoft.azure.PagedList)1 SecretIdentifier (com.microsoft.azure.keyvault.SecretIdentifier)1 Attributes (com.microsoft.azure.keyvault.models.Attributes)1 CertificateAttributes (com.microsoft.azure.keyvault.models.CertificateAttributes)1 CertificateBundle (com.microsoft.azure.keyvault.models.CertificateBundle)1 CertificateOperation (com.microsoft.azure.keyvault.models.CertificateOperation)1 CertificatePolicy (com.microsoft.azure.keyvault.models.CertificatePolicy)1 IssuerParameters (com.microsoft.azure.keyvault.models.IssuerParameters)1 KeyItem (com.microsoft.azure.keyvault.models.KeyItem)1 KeyVerifyResult (com.microsoft.azure.keyvault.models.KeyVerifyResult)1 SecretBundle (com.microsoft.azure.keyvault.models.SecretBundle)1 SecretProperties (com.microsoft.azure.keyvault.models.SecretProperties)1