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..5eb18bd42677a 100755 --- 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; @@ -153,7 +141,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..b3e1236542df2 100755 --- a/azure-keyvault-cryptography/pom.xml +++ b/azure-keyvault-cryptography/pom.xml @@ -34,30 +34,35 @@ HEAD - - UTF-8 - - - true - - - - - - junit - junit - test - - - org.bouncycastle - bcprov-jdk15on - test - 1.54 - - + + UTF-8 + + + true + + + + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk15on + test + 1.54 + + + ${project.groupId} + azure-keyvault-core + ${project.version} + + ${project.groupId} - azure-keyvault-core - ${project.version} - - + azure-keyvault-webkey + ${project.version} + + 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..e80ccaf5a76b0 100755 --- 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,35 +1,37 @@ /** - * - * 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.isNullOrEmpty(name)) { + if (Strings.isNullOrWhiteSpace(name)) { throw new IllegalArgumentException("name"); } _name = name; } + /** + * Gets the name of the algorithm. + * + * @return The name of the algorithm. + */ 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 1eacaad75e0c3..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 @@ -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; @@ -30,6 +18,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; @@ -38,46 +27,53 @@ 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(); - /// - /// 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/AsymmetricEncryptionAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java index 6a01e0333b0f2..b239a41d8530c 100755 --- 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 100755 --- 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..2c8af1810d836 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java @@ -0,0 +1,70 @@ +/** + * 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.util.Arrays; + +public final class ByteExtensions { + + 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 ); + } + + static byte[] xor( 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 void zero( byte[] self ) + { + if ( self != null ) { + Arrays.fill(self, (byte)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 100755 --- 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 100755 --- 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 100755 --- 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/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/KeyWrapAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java index fdc15bc1dad94..e0028d51a5073 100755 --- 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/RsaKey.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java index d8fe513c31c7b..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 @@ -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; @@ -22,15 +10,16 @@ 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; 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; @@ -43,28 +32,38 @@ 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); + } + + public RsaKey(String kid, int keySize, Provider provider) throws NoSuchAlgorithmException { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); } - final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider); 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"); @@ -77,25 +76,25 @@ 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 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() { - // TODO: Signature Processing - return null; + return Rs256.ALGORITHM_NAME; } @Override @@ -127,7 +126,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); @@ -157,7 +156,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); @@ -187,7 +186,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); @@ -221,7 +220,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); @@ -231,13 +230,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; + + ISignatureTransform signer = algo.createSignatureTransform(_keyPair); + + try { + return Futures.immediateFuture(Pair.of(signer.sign(digest), Rs256.ALGORITHM_NAME)); + } 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; + + ISignatureTransform signer = algo.createSignatureTransform(_keyPair); + + try { + return Futures.immediateFuture(signer.verify(digest, signature)); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } } @Override 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 100755 --- 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 c948e8e3453ab..a1ead94749e65 100755 --- 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,36 +1,34 @@ /** - * - * 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; -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/SymmetricEncryptionAlgorithm.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java index 4834485c31957..7c6e586fc09f8 100755 --- 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..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 @@ -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; @@ -78,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; @@ -101,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 206a463d5b7ef..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 @@ -1,29 +1,17 @@ /** - * - * 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; public class Aes128Cbc extends AesCbc { - public static final String AlgorithmName = "A128CBC"; + private static final int KEY_SIZE = 128; + public static final String ALGORITHM_NAME = "A128CBC"; public Aes128Cbc() { - super(AlgorithmName); + 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 eeb40fa3808b4..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 @@ -1,28 +1,16 @@ /** - * - * 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; 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 2cb0fc22b4d96..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 @@ -1,29 +1,17 @@ /** - * - * 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; public class Aes192Cbc extends AesCbc { - public static final String AlgorithmName = "A192CBC"; + private static final int KEY_SIZE = 192; + public static final String ALGORITHM_NAME = "A192CBC"; public Aes192Cbc() { - super(AlgorithmName); + super(ALGORITHM_NAME, KEY_SIZE); } - } 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..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 @@ -1,28 +1,16 @@ /** - * - * 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; 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 91fb58e09c932..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 @@ -1,29 +1,17 @@ /** - * - * 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; public class Aes256Cbc extends AesCbc { - public static final String AlgorithmName = "A256CBC"; + private static final int KEY_SIZE = 256; + public static final String ALGORITHM_NAME = "A256CBC"; public Aes256Cbc() { - super(AlgorithmName); + super(ALGORITHM_NAME, KEY_SIZE); } - } 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..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 @@ -1,28 +1,16 @@ /** - * - * 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; 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 7c49fba06c6b2..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 @@ -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; @@ -22,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; @@ -35,6 +24,8 @@ public abstract class AesCbc extends SymmetricEncryptionAlgorithm { + final int keySizeInBytes; + final int keySize; static class AesCbcDecryptor implements ICryptoTransform { private final Cipher _cipher; @@ -79,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 882a21284d616..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 @@ -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; @@ -224,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)); } @@ -239,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)); @@ -254,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/AesKw.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java index 8f7fa07ae6f12..6bd7dfc28c639 100755 --- 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 5d7a15605aea6..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 @@ -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; @@ -21,6 +9,8 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; import javax.crypto.NoSuchPaddingException; @@ -28,38 +18,40 @@ 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 - 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(Arrays.copyOfRange(key, 0, KeySizeInBytes), 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(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 f20f5ec7ee22c..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 @@ -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; @@ -21,6 +9,8 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; import javax.crypto.NoSuchPaddingException; @@ -28,38 +18,40 @@ 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 - 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(Arrays.copyOfRange(key, 0, KeySizeInBytes), 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(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 c4b23a572c222..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 @@ -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; @@ -21,6 +9,8 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; import javax.crypto.NoSuchPaddingException; @@ -28,38 +18,40 @@ 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 - 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(Arrays.copyOfRange(key, 0, KeySizeInBytes), 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(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 new file mode 100644 index 0000000000000..eddafecac6b28 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java @@ -0,0 +1,112 @@ +/** + * 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.NoSuchAlgorithmException; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; + +import com.microsoft.azure.keyvault.cryptography.ISignatureTransform; + +/** + * + */ +public class Rs256 extends RsaSignature { + + static final String RsaNone = "RSA/ECB/PKCS1Padding"; + + class Rs256SignatureTransform implements ISignatureTransform { + + private final KeyPair _keyPair; + private final int _emLen; + + Rs256SignatureTransform(KeyPair keyPair) { + _keyPair = keyPair; + + BigInteger modulus = ((RSAPublicKey)_keyPair.getPublic()).getModulus(); + + _emLen = getOctetLength( modulus.bitLength() ); + + } + + @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_HASH(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, _emLen ); + } + + @Override + public boolean verify(byte[] digest, byte[] signature) throws NoSuchAlgorithmException { + + if ( signature.length != _emLen ) { + throw new IllegalArgumentException( "invalid signature length"); + } + + // Convert to integer signature + BigInteger s = OS2IP(signature); + + // 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"); + + // Use constant time compare + return sequenceEqualConstantTime(EM, EM2); + } + + } + + public final static String ALGORITHM_NAME = "RS256"; + + public Rs256() { + super(ALGORITHM_NAME); + } + + @Override + 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 8161095756f88..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 @@ -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; @@ -84,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/RsaEncryption.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java index dd673f61ab416..83343057aa55a 100755 --- 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..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 @@ -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; @@ -84,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/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..84d2257ae2175 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java @@ -0,0 +1,210 @@ +/** + * 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; +import java.security.interfaces.RSAPublicKey; +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 { + + 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 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"); + } + + MessageDigest messageDigest = null; + + // Check algorithm + if ( Strings.isNullOrWhiteSpace(algorithm) ) { + throw new IllegalArgumentException("algorithm"); + } + + // Only supported algorithms + if ( algorithm.equals("SHA-256") ) { + + // Initialize digest + messageDigest = MessageDigest.getInstance("SHA-256"); + } else { + throw new IllegalArgumentException("algorithm"); + } + + // Hash the message + byte[] digest = messageDigest.digest(m); + + // Construct T, the DER encoded DigestInfo structure + 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(h, 0, T, algorithmPrefix.length, h.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; + } + + public abstract ISignatureTransform createSignatureTransform(KeyPair keyPair); +} 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 100755 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 100755 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/AesCbcBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java index c7d9c96b36702..043b2b54808be 100755 --- 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/AesCbcDefaultProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcDefaultProviderTest.java deleted file mode 100755 index 947ef7cddfc74..0000000000000 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcDefaultProviderTest.java +++ /dev/null @@ -1,120 +0,0 @@ -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 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 AesCbcDefaultProviderTest { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @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); - } 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); - } 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 100755 --- 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/AesCbcTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java new file mode 100644 index 0000000000000..b9bbf4a65e1e9 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java @@ -0,0 +1,230 @@ +package com.microsoft.azure.keyvault.cryptography.test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; + +import java.security.Provider; +import java.util.Arrays; + +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 AesCbcTest { + + private Provider _provider = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + 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 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(Arrays.copyOfRange(encrypted, 0, 16), 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(Arrays.copyOfRange(decrypted, 0, 16), 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(Arrays.copyOfRange(encrypted, 0, 32), 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(Arrays.copyOfRange(decrypted, 0, 32), 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(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(Arrays.copyOfRange(encrypted, 0, 16),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(Arrays.copyOfRange(decrypted, 0, 16), PLAIN); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @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(Arrays.copyOfRange(encrypted, 0, 32), 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(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/AesKwBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java index e1e7ce50c53f7..480db6f2e8966 100755 --- 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/AesKwDefaultProviderTest.java deleted file mode 100755 index a9b4495e9313a..0000000000000 --- a/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwDefaultProviderTest.java +++ /dev/null @@ -1,316 +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 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; -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 AesKwDefaultProviderTest { - - 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 void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - // Always null for the default provider - private Provider _provider = null; - - @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 }; - - /* - * 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); - - 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"); - } - - if (unlimited) { - 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); - 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"); - } - - if (unlimited) { - 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 }; - - /* - * 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); - 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"); - } - - if (unlimited) { - 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); - - 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"); - } - - if (unlimited) { - 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/AesKwTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java new file mode 100644 index 0000000000000..e79e5569fe71c --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java @@ -0,0 +1,429 @@ +/** + * + * 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.assertArrayEquals; +import static org.junit.Assert.fail; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import javax.crypto.Cipher; +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 AesKwTest { + + // Always null for the default provider + 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 void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + protected void setProvider(Provider provider) { + _provider = provider; + } + + @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 (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() { + // 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(); + 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() { + // 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(); + 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); + } + } + + @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/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..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 @@ -2,15 +2,10 @@ import static org.junit.Assert.*; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.spec.KeySpec; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.util.concurrent.Future; +import java.security.MessageDigest; +import java.security.Provider; +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,11 +14,22 @@ 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; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; 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 = { 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; @BeforeClass public static void setUpBeforeClass() throws Exception { @@ -40,165 +46,126 @@ public void setUp() throws Exception { @After public void tearDown() throws Exception { } - - @Test - public void testEncryptDecryptRsa15() throws Exception { - - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); - - // Encrypt the plaintext - Triple result = key.encryptAsync(plaintext, null, null, Rsa15.AlgorithmName).get(); - - byte[] ciphertext = result.getLeft(); - - 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); + + protected void setProvider(Provider provider) { + _provider = provider; } @Test - public void testEncryptDecryptRsaOaep() 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, RsaOaep.AlgorithmName).get(); + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, Rsa15.ALGORITHM_NAME).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.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(); - - key.close(); - - assertArrayEquals(plaintext, decrypted); - } - - @Test - public void testWrapUnwrapRsa15() throws Exception { - - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); + // Assert + assertEquals(Rsa15.ALGORITHM_NAME, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); - // Encrypt the plaintext - Pair result = key.wrapKeyAsync(plaintext, Rsa15.AlgorithmName).get(); + // Encrypt and Decrypt + Triple encrypted = key.encryptAsync(CEK, null, null, Rsa15.ALGORITHM_NAME).get(); + byte[] decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.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(); + // Assert + assertEquals(Rsa15.ALGORITHM_NAME, encrypted.getRight()); + assertArrayEquals(CEK, decrypted); key.close(); - - assertArrayEquals(plaintext, decrypted); } @Test - public void testWrapUnwrapRsaOaep() 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, RsaOaep.AlgorithmName).get(); + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, RsaOaep.ALGORITHM_NAME).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); - byte[] ciphertext = result.getLeft(); - - assertEquals(RsaOaep.AlgorithmName, result.getRight()); + // Assert + assertEquals(RsaOaep.ALGORITHM_NAME, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); - // Decrypt the ciphertext - Future decryptResult = key.unwrapKeyAsync(ciphertext, result.getRight()); - byte[] decrypted = decryptResult.get(); + // Encrypt and Decrypt + 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.ALGORITHM_NAME, 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.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(); - assertEquals(RsaOaep.AlgorithmName, result.getRight()); + // Assert + assertEquals(RsaOaep.ALGORITHM_NAME, 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.ALGORITHM_NAME, encrypted.getRight()); + assertArrayEquals(CEK, decrypted); key.close(); - - assertArrayEquals(plaintext, decrypted); } - + @Test - public void testWrapUnwrapDefaultAlgorithm() throws Exception { - - KeyPair keyPair = getTestKeyMaterial(); - RsaKey key = new RsaKey("foo", keyPair); - byte[] plaintext = "plaintext".getBytes(); - - // Encrypt the plaintext - Pair result = key.wrapKeyAsync(plaintext, null).get(); + public void testSignVerify() throws Exception { + + RsaKey key = getTestRsaKey(); + + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(CEK); + + byte[] crossPlatformHash = Base64.decodeBase64(CrossPlatformHash); + byte[] crossPlatformSignature = Base64.decodeBase64(CrossPlatformSignature); + + // Check the hash + 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(); + + // Check the signature + assertTrue(result); + assertArrayEquals(crossPlatformSignature, signature.getLeft()); - byte[] ciphertext = result.getLeft(); - - 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 static KeyPair getTestKeyMaterial() throws Exception { - - return getWellKnownKey(); - } - - private static KeyPair getWellKnownKey() throws Exception { - BigInteger modulus = new BigInteger("27266783713040163753473734334021230592631652450892850648620119914958066181400432364213298181846462385257448168605902438305568194683691563208578540343969522651422088760509452879461613852042845039552547834002168737350264189810815735922734447830725099163869215360401162450008673869707774119785881115044406101346450911054819448375712432746968301739007624952483347278954755460152795801894283389540036131881712321193750961817346255102052653789197325341350920441746054233522546543768770643593655942246891652634114922277138937273034902434321431672058220631825053788262810480543541597284376261438324665363067125951152574540779"); - BigInteger publicExponent = new BigInteger("65537"); - BigInteger privateExponent = new BigInteger("10466613941269075477152428927796086150095892102279802916937552172064636326433780566497000814207416485739683286961848843255766652023400959086290344987308562817062506476465756840999981989957456897020361717197805192876094362315496459535960304928171129585813477132331538577519084006595335055487028872410579127692209642938724850603554885478763205394868103298473476811627231543504190652483290944218004086457805431824328448422034887148115990501701345535825110962804471270499590234116100216841170344686381902328362376624405803648588830575558058257742073963036264273582756620469659464278207233345784355220317478103481872995809"); - BigInteger primeP = new BigInteger("175002941104568842715096339107566771592009112128184231961529953978142750732317724951747797764638217287618769007295505214923187971350518217670604044004381362495186864051394404165602744235299100790551775147322153206730562450301874236875459336154569893255570576967036237661594595803204808064127845257496057219227"); - BigInteger primeQ = new BigInteger("155807574095269324897144428622185380283967159190626345335083690114147315509962698765044950001909553861571493035240542031420213144237033208612132704562174772894369053916729901982420535940939821673277140180113593951522522222348910536202664252481405241042414183668723338300649954708432681241621374644926879028977"); - BigInteger primeExponentP = new BigInteger("79745606804504995938838168837578376593737280079895233277372027184693457251170125851946171360348440134236338520742068873132216695552312068793428432338173016914968041076503997528137698610601222912385953171485249299873377130717231063522112968474603281996190849604705284061306758152904594168593526874435238915345"); - BigInteger primeExponentQ = new BigInteger("80619964983821018303966686284189517841976445905569830731617605558094658227540855971763115484608005874540349730961777634427740786642996065386667564038755340092176159839025706183161615488856833433976243963682074011475658804676349317075370362785860401437192843468423594688700132964854367053490737073471709030801"); - BigInteger crtCoefficient = new BigInteger("2157818511040667226980891229484210846757728661751992467240662009652654684725325675037512595031058612950802328971801913498711880111052682274056041470625863586779333188842602381844572406517251106159327934511268610438516820278066686225397795046020275055545005189953702783748235257613991379770525910232674719428"); - - KeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent); - KeySpec privateKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficient); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - - return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); + + 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-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..2954df416105f 100755 --- 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 SymmetricKeyTest { @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/SymmetricKeyDefaultProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java similarity index 67% rename from azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyDefaultProviderTest.java rename to azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java index 9365b416988e3..b6d3194cae058 100755 --- 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/SymmetricKeyTest.java @@ -23,6 +23,7 @@ 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; @@ -36,7 +37,9 @@ import com.microsoft.azure.keyvault.cryptography.SymmetricKey; -public class SymmetricKeyDefaultProviderTest { +public class SymmetricKeyTest { + + private Provider _provider = null; private static boolean hasUnlimitedCrypto() { try { @@ -56,11 +59,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 testSymmetricKeyAesKw128() { @@ -69,7 +77,7 @@ public void testSymmetricKeyAesKw128() { 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); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; @@ -110,19 +118,13 @@ public void testSymmetricKeyAesKw128() { @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 }; + 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); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; @@ -186,7 +188,7 @@ public void testSymmetricKeyAesKw256() { * the limited case, it should fail with InvalidKeyException. */ boolean unlimited = hasUnlimitedCrypto(); - SymmetricKey key = new SymmetricKey("KEK", KEK); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; @@ -243,7 +245,7 @@ public void testSymmetricKeyDefaultAlgorithmAesKw128() { 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); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; String algorithm = null; @@ -299,7 +301,7 @@ public void testSymmetricKeyDefaultAlgorithmAesKw192() { * the limited case, it should fail with InvalidKeyException. */ boolean unlimited = hasUnlimitedCrypto(); - SymmetricKey key = new SymmetricKey("KEK", KEK); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; String algorithm = null; @@ -360,14 +362,13 @@ public void testSymmetricKeyDefaultAlgorithmAesKw256() { 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); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; String algorithm = null; @@ -421,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"); + } + } } diff --git a/azure-keyvault-extensions/pom.xml b/azure-keyvault-extensions/pom.xml index 3c9f92ea238a1..36d1dc3668e0a 100755 --- 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 485fa3a0b797f..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 @@ -29,12 +29,12 @@ 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.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.models.JsonWebKey; import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; -import com.microsoft.rest.ServiceResponse; /** * The key vault key that performs cryptography operations. @@ -44,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; @@ -69,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); } } @@ -97,7 +97,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)); } @@ -167,10 +167,10 @@ public ListenableFuture decryptAsync(byte[] ciphertext, byte[] iv, byte[ } // Never local - ListenableFuture> futureCall = + ListenableFuture futureCall = client.decryptAsync( implementation.getKid(), - algorithm, + new JsonWebKeyEncryptionAlgorithm(algorithm), ciphertext, null); return Futures.transform(futureCall, new DecryptResultTransform()); @@ -205,10 +205,10 @@ public ListenableFuture unwrapKeyAsync(byte[] ciphertext, String algorit } // Never local - ListenableFuture> futureCall = + ListenableFuture futureCall = client.unwrapKeyAsync( implementation.getKid(), - algorithm, + new JsonWebKeyEncryptionAlgorithm(algorithm), ciphertext, null); return Futures.transform(futureCall, new DecryptResultTransform()); @@ -225,10 +225,10 @@ public ListenableFuture> signAsync(byte[] digest, String al } // Never local - ListenableFuture> futureCall = + 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/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-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 100755 --- 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 */ 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..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 @@ -38,7 +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.rest.ServiceResponse; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; public class KeyVaultKeyResolverBCProviderTest extends KeyVaultClientIntegrationTestBase { @@ -79,9 +79,8 @@ 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(); - ServiceResponse response = keyVaultClient.createKey(request); - KeyBundle bundle = response != null ? response.getBody() : null; + CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); + KeyBundle bundle = keyVaultClient.createKey(request); if ( bundle != null ) { @@ -125,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 ) { @@ -185,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 ) { @@ -245,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 e6932d917cda1..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 @@ -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,8 +80,8 @@ 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(); - KeyBundle keyBundle = keyVaultClient.createKey(request).getBody(); + CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); + KeyBundle keyBundle = keyVaultClient.createKey(request); try { @@ -115,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 ) { @@ -175,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 ) { @@ -248,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-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..9418b15a96736 --- /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-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 new file mode 100644 index 0000000000000..eac3d33e26c7b --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java @@ -0,0 +1,38 @@ +/** + * 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.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +/** + * The base64 URL JSON serializer. + */ +public class Base64UrlJsonSerializer 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/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 58% 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 ed9bb700c1543..5d6dc8fe8b355 100755 --- 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,17 +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.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. */ @@ -44,79 +45,77 @@ public class JsonWebKey { * Key type, usually RSA. Possible values include: 'EC', 'RSA', 'RSA-HSM', * 'oct'. */ - private String kty; + private JsonWebKeyType kty; /** * The keyOps property. */ - @JsonProperty(value = "key_ops") - private List keyOps; + 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. */ - @JsonProperty(value = "K") - 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,312 +124,259 @@ 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. */ - public String kty() { + @JsonProperty("kty") + public JsonWebKeyType 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) { + public JsonWebKey withKty(JsonWebKeyType kty) { this.kty = kty; return this; } /** - * Get the keyOps value. + * Get the key operations. * - * @return the keyOps value + * @return the key operations. */ - public List keyOps() { + @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) { + public JsonWebKey withKeyOps(List keyOps) { this.keyOps = keyOps; return this; } /** - * 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; } @@ -472,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) { @@ -489,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) { @@ -507,7 +455,7 @@ private PrivateKey getRSAPrivateKey() { * 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"); } } @@ -589,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-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 new file mode 100755 index 0000000000000..67e5e99dd08c2 --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java @@ -0,0 +1,67 @@ +/** + * 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.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for JsonWebKeyEncryptionAlgorithm. + */ +public final class JsonWebKeyEncryptionAlgorithm { + /** Static value RSA-OAEP for JsonWebKeyEncryptionAlgorithm. */ + public static final JsonWebKeyEncryptionAlgorithm RSA_OAEP = new JsonWebKeyEncryptionAlgorithm("RSA-OAEP"); + + /** Static value RSA1_5 for JsonWebKeyEncryptionAlgorithm. */ + public static final JsonWebKeyEncryptionAlgorithm RSA1_5 = new JsonWebKeyEncryptionAlgorithm("RSA1_5"); + + private String value; + + /** + * Creates a custom value for JsonWebKeyEncryptionAlgorithm. + * @param value the custom value + */ + public JsonWebKeyEncryptionAlgorithm(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } + + @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 new file mode 100755 index 0000000000000..9dbb9d30fce67 --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java @@ -0,0 +1,79 @@ +/** + * 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.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for JsonWebKeyOperation. + */ +public final class JsonWebKeyOperation { + /** Static value encrypt for JsonWebKeyOperation. */ + public static final JsonWebKeyOperation ENCRYPT = new JsonWebKeyOperation("encrypt"); + + /** 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; + + /** + * Creates a custom value for JsonWebKeyOperation. + * @param value the custom value + */ + public JsonWebKeyOperation(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } + + @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 new file mode 100755 index 0000000000000..5e532c10cd297 --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java @@ -0,0 +1,73 @@ +/** + * 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.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for JsonWebKeySignatureAlgorithm. + */ +public final class JsonWebKeySignatureAlgorithm { + /** Static value RS256 for JsonWebKeySignatureAlgorithm. */ + public static final JsonWebKeySignatureAlgorithm RS256 = new JsonWebKeySignatureAlgorithm("RS256"); + + /** 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; + + /** + * Creates a custom value for JsonWebKeySignatureAlgorithm. + * @param value the custom value + */ + public JsonWebKeySignatureAlgorithm(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } + + @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 new file mode 100755 index 0000000000000..8a7c9dbffbc8e --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java @@ -0,0 +1,73 @@ +/** + * 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.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for JsonWebKeyType. + */ +public final class JsonWebKeyType { + /** Static value EC for JsonWebKeyType. */ + public static final JsonWebKeyType EC = new JsonWebKeyType("EC"); + + /** 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; + + /** + * Creates a custom value for JsonWebKeyType. + * @param value the custom value + */ + public JsonWebKeyType(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } + + @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/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 100755 --- 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 100755 --- 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/CertificateIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java index 334ad65b5f3d4..c78460edcfdec 100755 --- 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 100755 --- 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 100755 --- 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 100755 --- 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 52cbba1b6abbe..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 @@ -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; @@ -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; @@ -42,21 +41,23 @@ 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; -import retrofit2.Call; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Header; 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. @@ -180,7 +181,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); } /** @@ -191,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(), @@ -233,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(), @@ -273,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); } @@ -300,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(), @@ -339,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); @@ -367,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, ""); } @@ -395,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); } @@ -423,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> getKeyVersions(final String vaultBaseUrl, final String keyName) + public PagedList listKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName); } @@ -438,7 +439,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); } /** @@ -446,13 +447,13 @@ public ServiceCall> getKeyVersionsAsync(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> getKeyVersions(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); } @@ -462,11 +463,11 @@ public ServiceResponse> getKeyVersions(final String vaultBase * * @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 */ - 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); } @@ -477,9 +478,9 @@ public ServiceCall> getKeyVersionsAsync(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> getKeys(final String vaultBaseUrl) + public PagedList listKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeys(vaultBaseUrl); } @@ -491,20 +492,20 @@ 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); } /** * 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> getKeys(final String vaultBaseUrl, final Integer maxresults) + public PagedList listKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getKeys(vaultBaseUrl, maxresults); } @@ -513,11 +514,11 @@ public ServiceResponse> getKeys(final String vaultBaseUrl, fi * 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 */ - 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); } @@ -529,9 +530,9 @@ public ServiceCall> getKeysAsync(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); } @@ -556,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); } @@ -584,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, String 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); @@ -601,7 +602,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); } @@ -615,9 +616,9 @@ public ServiceCall encryptAsync(String keyIdentifier, String * @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, String 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); @@ -632,7 +633,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); } @@ -646,9 +647,9 @@ public ServiceCall decryptAsync(String keyIdentifier, String * @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, String 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); @@ -663,7 +664,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); } @@ -678,9 +679,9 @@ public ServiceCall signAsync(String keyIdentifier, String al * @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, String 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); @@ -696,7 +697,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); } @@ -710,9 +711,9 @@ public ServiceCall verifyAsync(String keyIdentifier, String alg * @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, String 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); @@ -727,7 +728,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); } @@ -741,9 +742,9 @@ public ServiceCall wrapKeyAsync(String keyIdentifier, String * @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, String 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); @@ -758,7 +759,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); } @@ -771,9 +772,9 @@ public ServiceCall unwrapKeyAsync(String keyIdentifier, Stri * @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(), @@ -811,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); } @@ -838,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(), @@ -877,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); @@ -905,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, ""); } @@ -933,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); } @@ -960,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> getSecrets(final String vaultBaseUrl) + public PagedList listSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecrets(vaultBaseUrl); } @@ -974,20 +975,20 @@ 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); } /** * 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> getSecrets(final String vaultBaseUrl, final Integer maxresults) + public PagedList listSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecrets(vaultBaseUrl, maxresults); } @@ -996,11 +997,11 @@ public ServiceResponse> getSecrets(final String vaultBaseU * 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 */ - 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); } @@ -1012,9 +1013,9 @@ public ServiceCall> getSecretsAsync(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> getSecretVersions(final String vaultBaseUrl, final String secretName) + public PagedList listSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName); } @@ -1027,7 +1028,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); } /** @@ -1035,13 +1036,13 @@ public ServiceCall> getSecretVersionsAsync(final String vaultBa * * @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> getSecretVersions(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); } @@ -1051,11 +1052,11 @@ public ServiceResponse> getSecretVersions(final String vau * * @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 */ - 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); } @@ -1066,9 +1067,9 @@ public ServiceCall> getSecretVersionsAsync(final String vaultBa * @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> getCertificates(final String vaultBaseUrl) + public PagedList listCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificates(vaultBaseUrl); } @@ -1080,20 +1081,20 @@ 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); } /** * 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> getCertificates(final String vaultBaseUrl, final Integer maxresults) + public PagedList listCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificates(vaultBaseUrl, maxresults); } @@ -1102,11 +1103,11 @@ public ServiceResponse> getCertificates(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 */ - 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); } @@ -1118,9 +1119,9 @@ public ServiceCall> getCertificatesAsync(final String vaul * @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); } @@ -1145,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); } @@ -1171,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); } @@ -1196,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); } @@ -1221,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> getCertificateIssuers(final String vaultBaseUrl) + public PagedList listCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl); } @@ -1235,20 +1236,20 @@ 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); } /** * 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> getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) + public PagedList listCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl, maxresults); } @@ -1257,11 +1258,11 @@ public ServiceResponse> getCertificateIssuers(f * 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 */ - 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); } @@ -1273,14 +1274,17 @@ public ServiceCall> getCertificateIssuersAsync(final * @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(), - setCertificateIssuerRequest.issuerName(), - setCertificateIssuerRequest.issuer()); + setCertificateIssuerRequest.issuerName(), + setCertificateIssuerRequest.provider(), + setCertificateIssuerRequest.credentials(), + setCertificateIssuerRequest.organizationDetails(), + setCertificateIssuerRequest.attributes()); } /** @@ -1295,7 +1299,10 @@ public ServiceCall setCertificateIssuerAsync(SetCertificateIssuerR return innerKeyVaultClient.setCertificateIssuerAsync( setCertificateIssuerRequest.vaultBaseUrl(), setCertificateIssuerRequest.issuerName(), - setCertificateIssuerRequest.issuer(), + setCertificateIssuerRequest.provider(), + setCertificateIssuerRequest.credentials(), + setCertificateIssuerRequest.organizationDetails(), + setCertificateIssuerRequest.attributes(), serviceCallback); } @@ -1307,14 +1314,17 @@ 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(), - updateCertificateIssuerRequest.issuerName(), - updateCertificateIssuerRequest.issuer()); + updateCertificateIssuerRequest.issuerName(), + updateCertificateIssuerRequest.provider(), + updateCertificateIssuerRequest.credentials(), + updateCertificateIssuerRequest.organizationDetails(), + updateCertificateIssuerRequest.attributes()); } /** @@ -1329,8 +1339,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); } @@ -1342,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); } @@ -1369,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); } @@ -1396,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(), @@ -1434,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(), @@ -1476,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> getCertificateVersions(final String vaultBaseUrl, final String certificateName) + public PagedList listCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName); } @@ -1491,7 +1504,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); } /** @@ -1499,13 +1512,13 @@ public ServiceCall> getCertificateVersionsAsync(final Stri * * @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> getCertificateVersions(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); } @@ -1515,11 +1528,11 @@ public ServiceResponse> getCertificateVersions(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 */ - 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); } @@ -1531,9 +1544,9 @@ public ServiceCall> getCertificateVersionsAsync(final Stri * @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); } @@ -1558,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(), @@ -1576,7 +1589,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(), @@ -1592,14 +1605,15 @@ public ServiceCall updateCertificatePolicy(UpdateCertificateP * @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(), - updateCertificateRequest.certificateName(), - updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificateName(), + updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificatePolicy(), updateCertificateRequest.certificateAttributes(), updateCertificateRequest.tags()); } @@ -1616,7 +1630,8 @@ public ServiceCall updateCertificateAsync(UpdateCertificateRe return innerKeyVaultClient.updateCertificateAsync( updateCertificateRequest.vaultBaseUrl(), updateCertificateRequest.certificateName(), - updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificatePolicy(), updateCertificateRequest.certificateAttributes(), updateCertificateRequest.tags(), serviceCallback); @@ -1629,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); @@ -1657,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, ""); } @@ -1685,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); } @@ -1713,14 +1728,14 @@ 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(), updateCertificateOperationRequest.certificateName(), - updateCertificateOperationRequest.certificateOperation()); + updateCertificateOperationRequest.cancellationRequested()); } /** @@ -1735,7 +1750,7 @@ public ServiceCall updateCertificateOperationAsync(UpdateC return innerKeyVaultClient.updateCertificateOperationAsync( updateCertificateOperationRequest.vaultBaseUrl(), updateCertificateOperationRequest.certificateName(), - updateCertificateOperationRequest.certificateOperation(), + updateCertificateOperationRequest.cancellationRequested(), serviceCallback); } @@ -1747,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); } @@ -1774,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); } @@ -1789,7 +1804,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); } @@ -1801,9 +1816,9 @@ ServiceCall deleteCertificateOperationAsync(String vaultBa * @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(), @@ -1840,23 +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 { - 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 getPendingCertificateSigningRequestWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -1868,9 +1871,17 @@ 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."); - } + return ServiceCall.create(getPendingCertificateSigningRequestWithServiceResponseAsync(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> getPendingCertificateSigningRequestWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1881,207 +1892,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; + }); } - - /** - * 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..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 @@ -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. @@ -9,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; @@ -17,14 +22,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.JsonWebKey; +import com.microsoft.azure.keyvault.models.IssuerCredentials; import com.microsoft.azure.keyvault.models.KeyAttributes; import com.microsoft.azure.keyvault.models.KeyBundle; import com.microsoft.azure.keyvault.models.KeyCreateParameters; @@ -38,27 +47,32 @@ 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; 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.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.ListOperationCallback; import com.microsoft.azure.Page; 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; @@ -71,6 +85,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. @@ -234,199 +250,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, @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); + 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, @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); + 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, @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); + 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); } @@ -435,38 +451,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. + * @return the KeyBundle object 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 KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty).toBlocking().single().getBody(); } /** @@ -474,11 +466,40 @@ 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(createKeyWithServiceResponseAsync(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 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 ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, String kty, final ServiceCallback serviceCallback) { + public Observable> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -492,7 +513,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(); @@ -502,26 +523,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); + 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.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -529,41 +542,18 @@ 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 * @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, 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 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(); } /** @@ -571,15 +561,52 @@ 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(createKeyWithServiceResponseAsync(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 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 ServiceCall createKeyAsync(String vaultBaseUrl, String keyName, String kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + 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."); } @@ -602,26 +629,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 { @@ -640,33 +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 { - 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()); + public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key).toBlocking().single().getBody(); } /** @@ -676,9 +672,38 @@ 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(importKeyWithServiceResponseAsync(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) { + 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."); } @@ -701,26 +726,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); + 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; + }); } /** @@ -735,32 +752,10 @@ public void onResponse(Call call, Response response) * @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 { - 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()); + 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(); } /** @@ -773,9 +768,44 @@ 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(importKeyWithServiceResponseAsync(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) { + 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."); } @@ -788,7 +818,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(); @@ -797,26 +826,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); - } - 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; + }); } private ServiceResponse importKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -834,21 +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 { - 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()); + public KeyBundle deleteKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().getBody(); } /** @@ -857,9 +867,36 @@ 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(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(); + } + }); + } + + /** + * 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> deleteKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -870,26 +907,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); + 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.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse deleteKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -908,31 +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 { - 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()); + public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single().getBody(); } /** @@ -942,22 +950,51 @@ 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) { - 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."); + return ServiceCall.create(updateKeyWithServiceResponseAsync(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) { + 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."); + } + 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 List keyOps = null; final KeyAttributes keyAttributes = null; final Map tags = null; KeyUpdateParameters parameters = new KeyUpdateParameters(); @@ -965,26 +1002,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; + }); } /** @@ -999,31 +1028,10 @@ public void onResponse(Call call, Response response) * @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 { - 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 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(); } /** @@ -1036,9 +1044,44 @@ 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(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 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) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).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 + * @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> 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."); } @@ -1059,26 +1102,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 { @@ -1097,24 +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 { - 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()); + public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single().getBody(); } /** @@ -1124,9 +1145,38 @@ 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(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(); + } + }); + } + + /** + * 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> getKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1140,26 +1190,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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1177,29 +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 { - 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()) { + public PagedList getKeyVersions(final String vaultBaseUrl, final String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName).toBlocking().single(); + return 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()); } /** @@ -1208,9 +1237,66 @@ 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 PagedList<KeyItem> object + */ + 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(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 PagedList<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."); } @@ -1222,32 +1308,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; + }); } /** @@ -1255,32 +1327,20 @@ 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 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 { - 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()) { + public PagedList getKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults).toBlocking().single(); + return 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()); } /** @@ -1288,11 +1348,71 @@ 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 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 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 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) { + 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1303,32 +1423,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 { @@ -1345,26 +1451,16 @@ 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()) { + public PagedList getKeys(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return 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()); } /** @@ -1372,9 +1468,63 @@ 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 PagedList<KeyItem> object + */ + 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeysNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the PagedList<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."); } @@ -1383,72 +1533,106 @@ 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; + }); } /** * 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 { - 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()) { + public PagedList getKeys(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return 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()); } /** * 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 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeysNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -1456,32 +1640,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 { @@ -1499,21 +1669,10 @@ 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()); + public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().getBody(); } /** @@ -1522,9 +1681,36 @@ 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(backupKeyWithServiceResponseAsync(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) { + 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."); } @@ -1535,26 +1721,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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse backupKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1572,23 +1750,10 @@ 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()); + public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup).toBlocking().single().getBody(); } /** @@ -1597,9 +1762,36 @@ 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(restoreKeyWithServiceResponseAsync(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) { + 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."); } @@ -1612,26 +1804,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 { @@ -1647,38 +1831,49 @@ 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 * @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, 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 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(); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback 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(); + } + }); } /** @@ -1687,12 +1882,11 @@ 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 + * @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> 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."); } @@ -1715,26 +1909,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 { @@ -1750,38 +1936,15 @@ 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 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(); } /** @@ -1790,12 +1953,45 @@ public ServiceResponse 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 + * @return the {@link ServiceCall} object */ - public ServiceCall decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + public ServiceCall decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(decryptWithServiceResponseAsync(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 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."); } @@ -1818,26 +2014,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); + 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.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse decryptDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1853,38 +2041,15 @@ private ServiceResponse decryptDelegate(Response sign(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."); - } - 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()); - return signDelegate(call.execute()); + 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(); } /** @@ -1893,12 +2058,45 @@ public ServiceResponse 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 + * @return the {@link ServiceCall} object + */ + public ServiceCall signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(signWithServiceResponseAsync(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) { + 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 ServiceCall signAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + 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."); } @@ -1921,26 +2119,18 @@ public ServiceCall signAsync(String vaultBaseUrl, String key 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); + 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); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse signDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -1956,43 +2146,16 @@ 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 * @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, 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 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(); } /** @@ -2001,13 +2164,48 @@ 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. - * @return the {@link Call} object + * @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(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(); + } + }); + } + + /** + * 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 ServiceCall verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { + 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."); } @@ -2034,26 +2232,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); + 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.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse verifyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2069,38 +2259,15 @@ 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 * @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, 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 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(); } /** @@ -2109,12 +2276,45 @@ 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 + * @return the {@link ServiceCall} object + */ + public ServiceCall wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(wrapKeyWithServiceResponseAsync(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 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 ServiceCall wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + 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."); } @@ -2137,26 +2337,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 { @@ -2172,38 +2364,49 @@ 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 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(); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceCall.create(unwrapKeyWithServiceResponseAsync(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) { + return unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1, KeyOperationResult>() { + @Override + public KeyOperationResult call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -2212,12 +2415,11 @@ public ServiceResponse 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 + * @return the observable to the KeyOperationResult object */ - public ServiceCall unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, byte[] value, final ServiceCallback serviceCallback) { + 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."); } @@ -2240,26 +2442,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); + 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.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse unwrapKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2278,32 +2472,10 @@ 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()); + public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value).toBlocking().single().getBody(); } /** @@ -2313,9 +2485,38 @@ 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(setSecretWithServiceResponseAsync(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) { + 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."); } @@ -2337,26 +2538,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; + }); } /** @@ -2371,31 +2564,10 @@ public void onResponse(Call call, Response response) * @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 { - 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()); + 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(); } /** @@ -2408,9 +2580,44 @@ 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(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(); + } + }); + } + + /** + * 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> 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."); } @@ -2431,26 +2638,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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse setSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2468,21 +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 { - 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()); + public SecretBundle deleteSecret(String vaultBaseUrl, String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteSecretWithServiceResponseAsync(vaultBaseUrl, secretName).toBlocking().single().getBody(); } /** @@ -2491,9 +2679,36 @@ 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(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(); + } + }); + } + + /** + * 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> deleteSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2504,26 +2719,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 { @@ -2542,31 +2749,10 @@ 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()); + public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single().getBody(); } /** @@ -2576,9 +2762,38 @@ 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(updateSecretWithServiceResponseAsync(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) { + 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."); } @@ -2599,26 +2814,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; + }); } /** @@ -2633,30 +2840,10 @@ public void onResponse(Call call, Response response) * @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 { - 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()); + 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(); } /** @@ -2669,9 +2856,44 @@ 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(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(); + } + }); + } + + /** + * 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> 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."); } @@ -2691,26 +2913,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 { @@ -2729,24 +2943,23 @@ 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()); + 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); } /** @@ -2755,10 +2968,26 @@ 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 Call} object + * @return the observable to the SecretBundle object */ - public ServiceCall getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback 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(); + } + }); + } + + /** + * 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> getSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String secretVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2772,26 +3001,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 { @@ -2808,26 +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 { - 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()) { + public PagedList getSecrets(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return 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()); } /** @@ -2835,9 +3046,63 @@ 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 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>> getSecretsWithServiceResponseAsync(final String vaultBaseUrl) { + return getSecretsSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the PagedList<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."); } @@ -2846,72 +3111,106 @@ 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; + }); } /** * 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 { - 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()) { + public PagedList getSecrets(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return 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()); } /** * 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 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -2919,32 +3218,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())); - } - } - 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; + }); } private ServiceResponse> getSecretsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -2962,29 +3247,16 @@ 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()) { + public PagedList getSecretVersions(final String vaultBaseUrl, final String secretName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName).toBlocking().single(); + return 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()); } /** @@ -2993,9 +3265,66 @@ 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretVersionsNextWithServiceResponseAsync(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 PagedList<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."); } @@ -3007,32 +3336,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; + }); } /** @@ -3040,32 +3355,20 @@ public void onResponse(Call call, Response 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 { - 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()) { + public PagedList getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults).toBlocking().single(); + return 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()); } /** @@ -3073,11 +3376,71 @@ 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 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 Call} object + * @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); + } + + /** + * 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) { + 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretVersionsNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3088,32 +3451,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())); - } + 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.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getSecretVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3130,26 +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 { - 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()) { + public PagedList getCertificates(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return 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()); } /** @@ -3157,9 +3496,63 @@ 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 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>> getCertificatesWithServiceResponseAsync(final String vaultBaseUrl) { + return getCertificatesSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the PagedList<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."); } @@ -3168,72 +3561,106 @@ 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; + }); } /** * 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> object 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()) { + public PagedList getCertificates(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return 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()); } /** * 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 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3241,32 +3668,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 { @@ -3284,21 +3697,38 @@ 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 { - 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()); + public CertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteCertificateWithServiceResponseAsync(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) { + return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.getBody(); + } + }); } /** @@ -3306,10 +3736,9 @@ 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 observable to the CertificateBundle object */ - public ServiceCall deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + public Observable> deleteCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3320,26 +3749,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 { @@ -3357,22 +3778,10 @@ 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()); + public Contacts setCertificateContacts(String vaultBaseUrl, Contacts contacts) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts).toBlocking().single().getBody(); } /** @@ -3381,9 +3790,36 @@ 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(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(); + } + }); + } + + /** + * 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> setCertificateContactsWithServiceResponseAsync(String vaultBaseUrl, Contacts contacts) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3395,26 +3831,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 { @@ -3431,18 +3859,10 @@ 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()); + public Contacts getCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateContactsWithServiceResponseAsync(vaultBaseUrl).toBlocking().single().getBody(); } /** @@ -3450,9 +3870,34 @@ 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(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(); + } + }); + } + + /** + * 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> getCertificateContactsWithServiceResponseAsync(String vaultBaseUrl) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3460,26 +3905,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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3496,18 +3933,10 @@ 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()); + public Contacts deleteCertificateContacts(String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateContactsWithServiceResponseAsync(vaultBaseUrl).toBlocking().single().getBody(); } /** @@ -3515,9 +3944,34 @@ 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(deleteCertificateContactsWithServiceResponseAsync(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) { + 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."); } @@ -3525,26 +3979,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 { @@ -3561,26 +4007,16 @@ 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()) { + public PagedList getCertificateIssuers(final String vaultBaseUrl) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return 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()); } /** @@ -3588,9 +4024,63 @@ 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 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>> getCertificateIssuersWithServiceResponseAsync(final String vaultBaseUrl) { + return getCertificateIssuersSinglePageAsync(vaultBaseUrl) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @return the PagedList<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."); } @@ -3599,72 +4089,106 @@ 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())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } /** * 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> object 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()) { + public PagedList getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return 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()); } /** * 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 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3672,32 +4196,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())); - } - } - serviceCall.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificateIssuersDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3712,29 +4222,106 @@ 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 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. + * @return the IssuerBundle object if successful. + */ + public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).toBlocking().single().getBody(); + } + + /** + * 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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback 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(); + } + }); + } + + /** + * 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 ServiceResponse setCertificateIssuer(String vaultBaseUrl, String issuerName, IssuerBundle issuer) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public Observable> setCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName, String provider) { 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()); - return setCertificateIssuerDelegate(call.execute()); + 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); + } + } + }); + } + + /** + * 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. + * @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 if successful. + */ + 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(); } /** @@ -3742,45 +4329,82 @@ 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 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(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(); + } + }); + } + + /** + * 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 ServiceCall setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, IssuerBundle issuer, final ServiceCallback serviceCallback) { + 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."); } 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."); + } + 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()); - 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; + }); } private ServiceResponse setCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -3795,29 +4419,100 @@ private ServiceResponse setCertificateIssuerDelegate(Response updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback 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(); + } + }); + } + + /** + * 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 ServiceResponse updateCertificateIssuer(String vaultBaseUrl, String issuerName, IssuerBundle issuer) throws KeyVaultErrorException, IOException, IllegalArgumentException { + public Observable> updateCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { 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); + final String provider = null; + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(null); + 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()); - return updateCertificateIssuerDelegate(call.execute()); + 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); + } + } + }); + } + + /** + * 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. + * @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 if successful. + */ + 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(); } /** @@ -3825,45 +4520,79 @@ 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 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(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(); + } + }); + } + + /** + * 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 ServiceCall updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, IssuerBundle issuer, final ServiceCallback serviceCallback) { + 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."); } 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); + 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()); - 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 { @@ -3881,21 +4610,10 @@ 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()); + public IssuerBundle getCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().getBody(); } /** @@ -3904,9 +4622,36 @@ 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(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(); + } + }); + } + + /** + * 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> getCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3917,26 +4662,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 { @@ -3954,21 +4691,10 @@ 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()); + public IssuerBundle deleteCertificateIssuer(String vaultBaseUrl, String issuerName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().getBody(); } /** @@ -3977,9 +4703,36 @@ 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(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(); + } + }); + } + + /** + * 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> deleteCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -3990,26 +4743,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 { @@ -4027,28 +4772,10 @@ 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()); + public CertificateOperation createCertificate(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -4057,9 +4784,36 @@ 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(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(); + } + }); + } + + /** + * 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> createCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4077,26 +4831,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; + }); } /** @@ -4110,28 +4856,10 @@ public void onResponse(Call call, Response response) * @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 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()); + 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(); } /** @@ -4143,9 +4871,42 @@ 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(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(); + } + }); + } + + /** + * 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> 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."); } @@ -4163,26 +4924,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); - } - 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; + }); } private ServiceResponse createCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4201,34 +4954,10 @@ 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 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()); + public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).toBlocking().single().getBody(); } /** @@ -4238,9 +4967,38 @@ 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(importCertificateWithServiceResponseAsync(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) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.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. + * @return the observable to the CertificateBundle object + */ + public Observable> importCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4264,26 +5022,37 @@ 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; + }); + } + + /** + * 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 + * @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 if successful. + */ + 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(); } /** @@ -4296,36 +5065,11 @@ public void onResponse(Call call, Response response) * @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 - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @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, 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()); + public ServiceCall importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags), serviceCallback); } /** @@ -4338,10 +5082,30 @@ 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) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.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 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> 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."); } @@ -4364,26 +5128,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); + 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.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse importCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4401,29 +5157,16 @@ 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()) { + public PagedList getCertificateVersions(final String vaultBaseUrl, final String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName).toBlocking().single(); + return 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()); } /** @@ -4432,9 +5175,66 @@ 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(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 PagedList<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."); } @@ -4446,32 +5246,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())); - } + 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.success(new ServiceResponse<>(result.getBody().getItems(), response)); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); - } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -4479,32 +5265,20 @@ 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 - * @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> object 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()) { + public PagedList getCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults).toBlocking().single(); + return 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()); } /** @@ -4512,11 +5286,71 @@ 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 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 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 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>> 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(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 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) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4527,32 +5361,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 { @@ -4570,21 +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 { - 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()); + public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -4593,9 +5402,36 @@ 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(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(); + } + }); + } + + /** + * 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> getCertificatePolicyWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4606,26 +5442,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 { @@ -4644,25 +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 { - 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()); + public CertificatePolicy updateCertificatePolicy(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy).toBlocking().single().getBody(); } /** @@ -4672,9 +5485,38 @@ 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(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(); + } + }); + } + + /** + * 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> updateCertificatePolicyWithServiceResponseAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4689,26 +5531,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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse updateCertificatePolicyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4727,29 +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 { - 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 CertificateAttributes certificateAttributes = null; - final Map tags = null; - CertificateUpdateParameters parameters = new CertificateUpdateParameters(); - 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()); + public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single().getBody(); } /** @@ -4759,9 +5574,38 @@ 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(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(); + } + }); + } + + /** + * 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> updateCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4774,32 +5618,44 @@ 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); - 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; + }); + } + + /** + * 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 + * @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 if successful. + */ + 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(); } /** @@ -4808,34 +5664,14 @@ 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 - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CertificateBundle object wrapped in {@link ServiceResponse} if successful. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object */ - public ServiceResponse updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, 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(certificateAttributes); - Validator.validate(tags); - CertificateUpdateParameters parameters = new CertificateUpdateParameters(); - 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()); + public ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags), serviceCallback); } /** @@ -4844,12 +5680,32 @@ 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 + * @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(); + } + }); + } + + /** + * 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 ServiceCall updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + 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."); } @@ -4862,32 +5718,26 @@ 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); - 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 { @@ -4906,24 +5756,10 @@ 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()); + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single().getBody(); } /** @@ -4933,9 +5769,38 @@ 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(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(); + } + }); + } + + /** + * 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> getCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, String certificateVersion) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -4949,26 +5814,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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse getCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -4983,29 +5840,14 @@ private ServiceResponse getCertificateDelegate(Response updateCertificateOperation(String vaultBaseUrl, String certificateName, CertificateOperation certificateOperation) 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); - String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); - Call call = service.updateCertificateOperation(certificateName, certificateOperation, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()); - return updateCertificateOperationDelegate(call.execute()); + public CertificateOperation updateCertificateOperation(String vaultBaseUrl, String certificateName, boolean cancellationRequested) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested).toBlocking().single().getBody(); } /** @@ -5013,45 +5855,64 @@ 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 + * @return the {@link ServiceCall} object + */ + public ServiceCall updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateCertificateOperationWithServiceResponseAsync(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) { + 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 ServiceCall updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, CertificateOperation certificateOperation, final ServiceCallback serviceCallback) { + public Observable> updateCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { 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()); - 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 { @@ -5069,21 +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 { - 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()); + public CertificateOperation getCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return getCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -5092,9 +5942,36 @@ 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(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(); + } + }); + } + + /** + * 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> getCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5105,26 +5982,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 { @@ -5142,21 +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 { - 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()); + public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().getBody(); } /** @@ -5165,9 +6023,36 @@ 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(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(); + } + }); + } + + /** + * 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> deleteCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5178,26 +6063,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 { @@ -5216,31 +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 { - 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()); + public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates).toBlocking().single().getBody(); } /** @@ -5250,9 +6106,38 @@ 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(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(); + } + }); + } + + /** + * 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> mergeCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName, List x509Certificates) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } @@ -5273,26 +6158,50 @@ 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); - } - serviceCall.success(clientResponse); - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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.failure(exception); } - } - }); - return serviceCall; + }); + } + + /** + * 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 + * @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 if successful. + */ + 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(); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceCall.create(mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags), serviceCallback); } /** @@ -5303,34 +6212,15 @@ public void onResponse(Call call, Response response) * @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 - * @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 observable to the CertificateBundle object */ - 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()); + 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(); + } + }); } /** @@ -5341,10 +6231,9 @@ public ServiceResponse mergeCertificate(String vaultBaseUrl, * @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 - * @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 mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + 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."); } @@ -5365,26 +6254,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 { @@ -5401,14 +6282,16 @@ 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 PagedList getKeyVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5417,35 +6300,78 @@ 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 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>> getKeyVersionsNextWithServiceResponseAsync(final String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List the versions of the specified key. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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())); - } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getKeyVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5462,14 +6388,16 @@ 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 PagedList getKeysNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getKeysNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5478,35 +6406,78 @@ 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 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>> getKeysNextWithServiceResponseAsync(final String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeysNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List keys in the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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 { @@ -5523,14 +6494,16 @@ 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 PagedList getSecretsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5539,35 +6512,78 @@ 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 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>> getSecretsNextWithServiceResponseAsync(final String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List secrets in the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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())); - } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getSecretsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5584,14 +6600,16 @@ 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 PagedList getSecretVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5600,35 +6618,78 @@ 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 PagedList<SecretItem> object + */ + 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(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretVersionsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List the versions of the specified secret. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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 { @@ -5645,14 +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 { - 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 PagedList getCertificatesNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5661,35 +6724,78 @@ 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 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>> getCertificatesNextWithServiceResponseAsync(final String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificates in the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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())); - } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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); } - serviceCall.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> getCertificatesNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { @@ -5706,14 +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 { - 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 PagedList getCertificateIssuersNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5722,35 +6830,78 @@ 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 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>> getCertificateIssuersNextWithServiceResponseAsync(final String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificate issuers for the specified vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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 { @@ -5767,14 +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 { - 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 PagedList getCertificateVersionsNext(final String nextPageLink) throws KeyVaultErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -5783,35 +6936,78 @@ 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 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>> getCertificateVersionsNextWithServiceResponseAsync(final String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List the versions of a certificate. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<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())); - } - } catch (KeyVaultErrorException | IOException exception) { - if (serviceCallback != null) { - serviceCallback.failure(exception); + 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); } - 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/ObjectIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java index 290a07c94003e..e026b82b7d9ae 100755 --- 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 100755 --- 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..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 @@ -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; @@ -22,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/authentication/KeyVaultCredentials.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java index ad1a3e8206271..9c184cb7cea5b 100755 --- 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/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 100755 --- 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/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 new file mode 100644 index 0000000000000..df352850dff30 --- /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 issuer provider. + */ + @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..05d62b4ec54d9 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java @@ -0,0 +1,120 @@ +/** + * 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 update parameters. + */ +public class CertificateIssuerUpdateParameters { + /** + * The issuer provider. + */ + 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 100755 --- 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..b2cd7b05f1189 --- /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; + +/** + * The certificate operation update parameters. + */ +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 100755 --- 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..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 @@ -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. @@ -29,7 +30,7 @@ public class IssuerBundle { private String id; /** - * The name of the issuer. + * The issuer provider. */ private String provider; @@ -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/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 4c13b1490a64d..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 @@ -17,6 +17,9 @@ 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; +import com.fasterxml.jackson.annotation.JsonProperty; /** * A KeyBundle consisting of a WebKey plus its Attributes. @@ -37,6 +40,13 @@ public class KeyBundle { */ private Map tags; + /** + * 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; + /** * Get the key value. * @@ -97,6 +107,15 @@ public KeyBundle withTags(Map tags) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + /** * The key identifier. * @return identifier for the key @@ -110,7 +129,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/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/KeyImportParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java index 0cd6eb0a956e5..457486131b8c7 100755 --- 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/models/KeyItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java index 05584de30f1ac..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 @@ -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. @@ -33,6 +34,13 @@ public class KeyItem { */ private Map tags; + /** + * 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; + /** * Get the kid value. * @@ -93,6 +101,15 @@ public KeyItem withTags(Map tags) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + /** * The key identifier. * @return The Identifier value 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/KeyVaultErrorException.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java index bdcfc617fc14c..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 @@ -29,6 +29,16 @@ 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 super.getMessage(); + } /** * Initializes a new instance of the KeyVaultErrorException class. * 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 52d7e736fb451..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 @@ -13,10 +13,12 @@ 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; import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; /** * A Secret consisting of a value, id and its attributes. @@ -48,10 +50,19 @@ 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 i.e. if this is a + * secret backing a certificate, then managed will be true. + */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + private Boolean managed; + /** * Get the value value. * @@ -162,14 +173,12 @@ public String kid() { } /** - * Set the kid value. + * Get the managed value. * - * @param kid the kid value to set - * @return the SecretBundle object itself. + * @return the managed value */ - public SecretBundle withKid(String kid) { - this.kid = kid; - return this; + public Boolean managed() { + return this.managed; } /** @@ -185,7 +194,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/models/SecretItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java index 5359f9cba67ca..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 @@ -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. @@ -38,6 +39,13 @@ public class SecretItem { */ private String contentType; + /** + * 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; + /** * Get the id value. * @@ -118,6 +126,15 @@ public SecretItem withContentType(String contentType) { return this; } + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + /** * the secret identifier. * @return The Identifier value 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/CreateCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java index fb9a8e5db704b..84900c5ae2143 100755 --- 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..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 @@ -5,7 +5,10 @@ import java.util.List; import java.util.Map; +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. @@ -14,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; @@ -28,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; @@ -44,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; @@ -72,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; } @@ -84,8 +88,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; } @@ -119,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; } @@ -155,7 +159,7 @@ public String keyName() { /** * @return the key type */ - public String keyType() { + public JsonWebKeyType keyType() { return keyType; } @@ -169,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/ImportCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java index 56f04bd98a454..431c595ca9709 100755 --- 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..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 @@ -4,8 +4,10 @@ import java.util.Collections; import java.util.Map; -import com.microsoft.azure.keyvault.models.JsonWebKey; +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. @@ -71,8 +73,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; } @@ -109,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/MergeCertificateRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java index 9ad223c6a4816..1a1569e41d97c 100755 --- 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/SetCertificateIssuerRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java index 5c2d00f4d82e6..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 @@ -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 attributes + * 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/SetSecretRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java index a34c08d296f73..2bfa1cc3c6bc4 100755 --- 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/UpdateCertificateIssuerRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java index 633d16a2e7a70..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 @@ -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. @@ -21,7 +28,10 @@ public static class Builder { private final String issuerName; // Optional parameters - private IssuerBundle issuer; + private String provider; + private IssuerCredentials credentials; + private OrganizationDetails organizationDetails; + private IssuerAttributes attributes; /** * The builder for constructing {@link UpdateCertificateIssuerRequest} @@ -38,14 +48,50 @@ public Builder(String vaultBaseUrl, String issuerName) { } /** - * Set the issuer value. + * Set issuer credentials. * - * @param issuer - * The issuer bundle. + * @param provider + * The issuer provider. * @return the Builder object itself. */ - public Builder withIssuer(IssuerBundle issuer) { - this.issuer = issuer; + public Builder withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * 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 organizationDetails + * The issuer organization details. + * @return the Builder object itself. + */ + public Builder withOrganizationDetails(OrganizationDetails organizationDetails) { + this.organizationDetails = organizationDetails; + return this; + } + + /** + * Set issuer attributes. + * + * @param attributes + * The issuer attributes. + * @return the Builder object itself. + */ + public Builder withAttributes(IssuerAttributes attributes) { + this.attributes = attributes; return this; } @@ -62,16 +108,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 { + 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 { - issuer = null; + attributes = null; } } @@ -90,9 +145,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 100755 --- 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 100755 --- 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..b1403613b462d 100755 --- 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.Attributes; 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; /** * 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. @@ -61,8 +84,8 @@ public Builder withCertificateVersion(String version) { * 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; } @@ -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/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java index d87b8c798c583..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 @@ -6,7 +6,9 @@ import java.util.Map; 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. @@ -16,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; @@ -31,7 +33,7 @@ public static class Builder { // Optional parameters private String keyVersion; - private List keyOperations; + private List keyOperations; private KeyAttributes attributes; private Map tags; @@ -82,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; } @@ -94,8 +96,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; } @@ -128,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; } @@ -171,7 +173,7 @@ public String keyVersion() { /** * @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/UpdateSecretRequest.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java index 732aa8843ae33..e56f9f7713e28 100755 --- 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/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java deleted file mode 100755 index 96ee1a2d303e8..0000000000000 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java +++ /dev/null @@ -1,51 +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.webkey; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Supported JsonWebKey Algorithms. - */ -public final class JsonWebKeyEncryptionAlgorithm { - - /** - * The 'RSA-OAEP' algorithm. - */ - public static final String RSAOAEP = "RSA-OAEP"; - - /** - * The 'RSA1_5' algorithm. - */ - public static final String RSA15 = "RSA1_5"; - - /** - * All the JWK encryption algorithms. - */ - public static final List ALL_ALGORITHMS = - Collections.unmodifiableList( - Arrays.asList(new String[] {RSA15, RSAOAEP})); - - private JsonWebKeyEncryptionAlgorithm() { - // not instantiable - } - -} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java deleted file mode 100755 index 50360fee81496..0000000000000 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java +++ /dev/null @@ -1,71 +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.webkey; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Supported JsonWebKey operations. - */ -public final class JsonWebKeyOperation { - - /** - * 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"; - - /** - * All JWK operations. - */ - public static final List ALL_OPERATIONS = - Collections.unmodifiableList( - Arrays.asList(new String[] {ENCRYPT, DECRYPT, SIGN, VERIFY, WRAP, UNWRAP })); - - private JsonWebKeyOperation() { - // not instantiable - } - -} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java deleted file mode 100755 index fa9737305d268..0000000000000 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java +++ /dev/null @@ -1,60 +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.webkey; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Supported JsonWebKey Algorithms. - */ -public final class JsonWebKeySignatureAlgorithm { - - /** - * 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"; - - /** - * All JWK algorithms. - */ - public static final List ALL_ALGORITHMS = - Collections.unmodifiableList( - Arrays.asList(new String[] {RS256, RS384, RS512, RSNULL})); - - private JsonWebKeySignatureAlgorithm() { - // not instantiable - } -} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java deleted file mode 100755 index a04d9b3c40540..0000000000000 --- a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java +++ /dev/null @@ -1,60 +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.webkey; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Supported JsonWebKey key types (kty). - */ -public final class JsonWebKeyType { - - /** - * 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"; - - /** - * All JWK key types. - */ - public static final List ALL_TYPES = - Collections.unmodifiableList( - Arrays.asList(new String[] {EC, RSA, RSAHSM, OCT})); - - private JsonWebKeyType() { - // not instantiable - } -} 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..878603707842f --- /dev/null +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java @@ -0,0 +1,271 @@ +/** + * 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; + +import java.security.MessageDigest; +import java.util.HashMap; +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; + +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.KeyVaultErrorException; +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; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; + + +public class AsyncOperationsTest extends KeyVaultClientIntegrationTestBase { + + @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 keyItems = keyVaultClient.listKeysAsync(vault, 2, null).get(); + Assert.assertNotNull(keyItems); + + List 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); + + //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 + 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(); + Assert.assertNotNull(secretBundle); + + UpdateSecretRequest updateSecretRequest = new UpdateSecretRequest.Builder(secretBundle.id()).build(); + secretBundle = keyVaultClient.updateSecretAsync(updateSecretRequest, null).get(); + Assert.assertNotNull(secretBundle); + + secretBundle = keyVaultClient.getSecretAsync(secretBundle.id(), null).get(); + Assert.assertNotNull(secretBundle); + + List secretItems = keyVaultClient.listSecretsAsync(vault, 2, null).get(); + Assert.assertNotNull(secretItems); + + List secretVersionItems = keyVaultClient.listSecretVersionsAsync(vault, secretname, 2, null).get(); + Assert.assertNotNull(secretVersionItems); + + secretBundle = keyVaultClient.deleteSecretAsync(vault, secretname, null).get(); + 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 + 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(); + Assert.assertNotNull(certificateOperation); + + UpdateCertificateOperationRequest updateCertificateOperationRequest = new UpdateCertificateOperationRequest.Builder(vault, certificateName, false).build(); + 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(); + Assert.assertNotNull(certificateBundle); + + UpdateCertificatePolicyRequest updateCertificatePolicyRequest = new UpdateCertificatePolicyRequest.Builder(vault, certificateName).build(); + CertificatePolicy certificatePolicy = keyVaultClient.updateCertificatePolicyAsync(updateCertificatePolicyRequest, null).get(); + Assert.assertNotNull(certificatePolicy); + + certificatePolicy = keyVaultClient.getCertificatePolicyAsync(vault, certificateName, null).get(); + Assert.assertNotNull(certificatePolicy); + + certificateOperation = keyVaultClient.getCertificateOperationAsync(vault, certificateName, null).get(); + Assert.assertNotNull(certificateOperation); + + certificateBundle = keyVaultClient.getCertificateAsync(vault, certificateName, null).get(); + Assert.assertNotNull(certificateBundle); + + String cert = keyVaultClient.getPendingCertificateSigningRequestAsync(vault, certificateName, null).get(); + Assert.assertTrue(!cert.isEmpty()); + + List certificateItem = keyVaultClient.listCertificatesAsync(vault, null).get(); + Assert.assertNotNull(certificateItem); + + List certificateVersionItem = keyVaultClient.listCertificateVersionsAsync(vault, certificateName, null).get(); + Assert.assertNotNull(certificateVersionItem); + + + keyVaultClient.deleteCertificateOperationAsync(vault, certificateName, null).get(); + keyVaultClient.deleteCertificateAsync(vault, certificateName, null).get(); + + 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 + 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(); + Assert.assertNotNull(certificateIssuer); + + UpdateCertificateIssuerRequest updateCertificateIssuerRequest = new UpdateCertificateIssuerRequest.Builder(vault, issuerName).withProvider("SslAdmin").build(); + certificateIssuer = keyVaultClient.updateCertificateIssuerAsync(updateCertificateIssuerRequest, null).get(); + Assert.assertNotNull(certificateIssuer); + + certificateIssuer = keyVaultClient.getCertificateIssuerAsync(vault, issuerName, null).get(); + Assert.assertNotNull(certificateIssuer); + + List issuers = keyVaultClient.listCertificateIssuersAsync(vault, null).get(); + Assert.assertNotNull(issuers); + + keyVaultClient.deleteCertificateIssuerAsync(vault, issuerName, null).get(); + } + + + @Test + public void certificateContactsAsync() throws Exception { + + String vault = getVaultUri(); + + Contacts contacts = keyVaultClient.setCertificateContactsAsync(vault, new Contacts(), null).get(); + Assert.assertNotNull(contacts); + + contacts = keyVaultClient.getCertificateContactsAsync(vault, null).get(); + 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..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 @@ -1,33 +1,22 @@ /** - * - * 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; 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 +24,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,19 +39,24 @@ import javax.crypto.NoSuchPaddingException; import org.apache.commons.codec.binary.Base64; +import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; 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; import com.microsoft.azure.keyvault.models.Contacts; 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; @@ -73,814 +69,596 @@ 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); + + 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.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()); + + 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); + 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()); + + 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()); + + 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()); + Assert.assertTrue(secret.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.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()); + 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()); + + 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); + 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()); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + Assert.assertNotNull(certificateOperation.csr()); + + String csr = keyVaultClient.getPendingCertificateSigningRequest(vaultUri, certificateName); + Assert.assertNotNull(csr); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); + 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()); + + CertificateOperation cancelledCertificateOperation = keyVaultClient.updateCertificateOperation( + new UpdateCertificateOperationRequest + .Builder(vaultUri, certificateName, true) + .build()); + + Assert.assertNotNull(cancelledCertificateOperation); + Assert.assertTrue(cancelledCertificateOperation.cancellationRequested()); + + keyVaultClient.deleteCertificateOperation(getVaultUri(), certificateName); + keyVaultClient.deleteCertificate(getVaultUri(), certificateName); + } + + /** + * 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); + Attributes attribute = 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()); + + // 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()); + Assert.assertTrue(secret.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); + + 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()); + + + 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(attribute.withEnabled(false)) + .withTags(sTags) + .build()); + 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()); + Assert.assertEquals(certificatePolicyUpdate.issuerReference().name(), updatedCertificatePolicy.issuerReference().name()); + + CertificatePolicy policy = keyVaultClient.getCertificatePolicy(vaultUri, certificateName); + 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()); + CertificateIdentifier id = certificateBundle.certificateIdentifier(); + certificates.add(id.baseIdentifier()); + break; } catch (KeyVaultErrorException e) { ++failureCount; if (e.getBody().error().code().equals("Throttled")) { @@ -890,56 +668,58 @@ 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); + 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()); - 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()); - - 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()); + CertificateIdentifier id = certificateBundle.certificateIdentifier(); + certificates.add(id.identifier()); + break; } catch (KeyVaultErrorException e) { ++failureCount; if (e.getBody().error().code().equals("Throttled")) { @@ -949,320 +729,403 @@ 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); Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.getCertificateVersions(getVaultUri(), certificateName).getBody(); - for (;;) { - for (CertificateItem item : listResult) { + listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName); + + for (CertificateItem item : listResult) { + if(item != null) { certificates.remove(item.id()); } - String nextLink = listResult.nextPageLink(); - if (nextLink == null) { - break; - } - keyVaultClient.getCertificateVersionsNext(nextLink).getBody(); } 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(); - 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("-", ""); - } + } + + /** + * 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()); + + validateCertificateIssuer(certificateIssuer, createdCertificateIssuer); + + String certificateIssuerName = createdCertificateIssuer.issuerIdentifier().name(); + IssuerBundle retrievedCertificateIssuer = keyVaultClient.getCertificateIssuer(getVaultUri(), + certificateIssuerName); + + validateCertificateIssuer(certificateIssuer, retrievedCertificateIssuer); + + IssuerCredentials updatedCredentials = new IssuerCredentials() + .withAccountId("account2") + .withPassword("Secur!Ty"); + + retrievedCertificateIssuer.withCredentials(updatedCredentials); + IssuerBundle updatedCertificateIssuer = keyVaultClient.updateCertificateIssuer( + new UpdateCertificateIssuerRequest + .Builder(getVaultUri(), certificateIssuerName) + .withProvider(ISSUER_TEST) + .withCredentials(updatedCredentials) + .withOrganizationDetails(retrievedCertificateIssuer.organizationDetails()) + .withAttributes(retrievedCertificateIssuer.attributes()) + .build()); + + validateCertificateIssuer(retrievedCertificateIssuer, updatedCertificateIssuer); + + Assert.assertNotNull(updatedCertificateIssuer.organizationDetails()); + + IssuerBundle deletedCertificateIssuer = keyVaultClient.deleteCertificateIssuer(getVaultUri(), certificateIssuerName); + + 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); + 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()); + Assert.assertNotNull(retrievedCertificateContacts); + Assert.assertNotNull(retrievedCertificateContacts.contactList()); + Assert.assertTrue(retrievedCertificateContacts.contactList().size() == 2); + + // Delete + 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()); + } 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); + if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)) { + Thread.sleep(10000); + pendingPollCount += 1; + continue; + } + + if (pendingCertificateOperation.status().equalsIgnoreCase(STATUS_COMPLETED)) { + return keyVaultClient.getCertificate(pendingCertificateOperation.target()); + } + + 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("-", ""); + } + + 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()); + Assert.assertTrue(secret.managed()); + 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..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 @@ -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; @@ -47,7 +35,9 @@ 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.JsonWebKey; +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.JsonWebKeyEncryptionAlgorithm; import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; @@ -64,15 +54,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); + 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, JsonWebKeyType.RSA) + .withAttributes(attribute) + .withKeyOperations(keyOps) + .withKeySize(2048) + .withTags(tags) + .build()); + + 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); + KeyBundle bundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); + validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } } @@ -92,13 +97,24 @@ public void importKeyOperation() throws Exception { } 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 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()); + + validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? JsonWebKeyType.RSA_HSM : JsonWebKeyType.RSA, importedJwk.keyOps(), attribute); checkEncryptDecryptSequence(importedJwk, importResultBundle); } @@ -111,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); cipherText = result.result(); } @@ -136,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); byte[] beforeEncrypt = plainText; byte[] afterDecrypt = result.result(); @@ -150,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); + createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); } // Key identifier. @@ -159,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); } @@ -192,10 +208,10 @@ 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)); - List key_ops = Arrays.asList("encrypt", "decrypt"); + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2050)); + List key_ops = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); Map tags = new HashMap(); tags.put("foo", "baz"); createdBundle.key().withKeyOps(key_ops); @@ -203,12 +219,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()); compareKeyBundles(createdBundle, updatedBundle); @@ -220,38 +236,38 @@ 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)); - List key_ops = Arrays.asList("sign", "verify"); + createdBundle.attributes().withNotBefore(new DateTime() + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2000)); + List key_ops = Arrays.asList(JsonWebKeyOperation.SIGN, JsonWebKeyOperation.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()); compareKeyBundles(createdBundle, updatedBundle); } { // Delete key - KeyBundle deleteBundle = keyVaultClient.deleteKey(getVaultUri(), KEY_NAME).getBody(); + KeyBundle deleteBundle = keyVaultClient.deleteKey(getVaultUri(), KEY_NAME); compareKeyBundles(createdBundle, deleteBundle); } { // 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,15 +284,15 @@ 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, 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).getBody().value(); + keyBackup = keyVaultClient.backupKey(getVaultUri(), KEY_NAME).value(); } // Deletes the key. @@ -286,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); } @@ -300,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()); KeyIdentifier kid = new KeyIdentifier(createdBundle.key().kid()); keys.add(kid.baseIdentifier()); break; @@ -316,28 +332,30 @@ public void listKeys() throws Exception { } } - PagedList listResult = keyVaultClient.getKeys(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(); 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()); 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; + } } } @@ -349,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()); keys.add(createdBundle.key().kid()); break; } catch (KeyVaultErrorException e) { @@ -364,20 +382,15 @@ public void listKeyVersions() throws Exception { } } - PagedList listResult = keyVaultClient.getKeyVersions(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.getKeyVersions(getVaultUri(), KEY_NAME).getBody(); + listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME); - for (;;) { - for (KeyItem item : listResult) { + for (KeyItem item : listResult) { + if(item != null) { keys.remove(item.kid()); } - String nextLink = listResult.nextPageLink(); - if (nextLink == null) { - break; - } - keyVaultClient.getKeyVersionsNext(nextLink).getBody(); } Assert.assertEquals(0, keys.size()); @@ -400,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); cipherText = result.result(); - result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, 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.RSAOAEP, plainText).getBody(); + result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); - result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); + result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); Assert.assertArrayEquals(plainText, result.result()); } } @@ -432,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); cipherText = result.result(); - result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, 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.RSAOAEP, plainText).getBody(); + result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); cipherText = result.result(); - result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, cipherText).getBody(); + result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); Assert.assertArrayEquals(plainText, result.result()); } } @@ -468,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()); } @@ -492,21 +505,21 @@ 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 - .Builder(getVaultUri(), KEY_NAME, key) - .withHsm(false) - .build()).getBody(); + new ImportKeyRequest + .Builder(getVaultUri(), KEY_NAME, key) + .withHsm(false) + .build()); - validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, "RSA", null); + validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); return keyBundle.key(); } private static KeyPair getTestKeyMaterial() throws Exception { - return getWellKnownKey(); + return getWellKnownKey(); } private static KeyPair getWellKnownKey() throws Exception { @@ -526,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) 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( @@ -540,16 +553,20 @@ 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()); + + Assert.assertTrue(bundle.managed() == null || bundle.managed() == false); } 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..d3deb5fcb23f5 100755 --- 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; @@ -25,6 +13,7 @@ import org.junit.After; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -37,6 +26,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 +85,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 +126,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..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 @@ -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; @@ -25,7 +13,9 @@ 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; import com.microsoft.azure.PagedList; import com.microsoft.azure.keyvault.SecretIdentifier; @@ -45,17 +35,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); + Attributes attributes = 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()); + 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()); + validateSecret(secret, getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); } } @@ -63,12 +66,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()); + validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); } // Secret identifier. @@ -76,47 +79,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()); 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); } { - 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()); compareSecrets(secret, updatedSecret); // Subsequent operations must use the updated bundle for comparison. @@ -126,37 +129,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()); 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); 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,16 +173,15 @@ public void crudOperations() throws Exception { } - @Test - public void listSecrets() throws Exception { - + @Test + public void listSecrets() throws Exception { HashSet secrets = new HashSet(); for (int i = 0; i < MAX_SECRETS; ++i) { int failureCount = 0; 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; @@ -190,28 +197,30 @@ public void listSecrets() throws Exception { } } - PagedList listResult = keyVaultClient.getSecrets(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(); 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()); 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 +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) { @@ -239,19 +248,14 @@ 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); Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().getItems().size()); - listResult = keyVaultClient.getSecretVersions(getVaultUri(), SECRET_NAME).getBody(); - for (;;) { - for (SecretItem item : listResult) { + listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME); + for (SecretItem item : listResult) { + if(item != null) { secrets.remove(item.id()); } - String nextLink = listResult.nextPageLink(); - if (nextLink == null) { - break; - } - keyVaultClient.getSecretVersionsNext(nextLink).getBody(); } Assert.assertEquals(0, secrets.size()); @@ -259,7 +263,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, Attributes attributes) throws Exception { String prefix = vault + "/secrets/" + name + "/"; String id = secret.id(); Assert.assertTrue( // @@ -271,17 +275,22 @@ 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()); + + Assert.assertTrue(secret.managed() == null || secret.managed() == false); } 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())); + + } }