diff --git a/.gitignore b/.gitignore index f1e3d20e0568..9d6304e11c8f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,252 +1,56 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. +*.class -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates +#External libs +extlib/ -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs +# Auth files +*.auth +*.azureauth -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ +# Local checkstyle +*.checkstyle -# Visual Studio 2015 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ +# Mobile Tools for Java (J2ME) +.mtj.tmp/ -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* +# Package Files # +*.jar +*.war +*.ear -# NUNIT -*.VisualState.xml -TestResult.xml +# Azure Tooling # +node_modules +packages -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# DNX -project.lock.json -artifacts/ - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh +# Eclipse # +*.pydevproject +.project +.metadata +bin/** +tmp/** +tmp/**/* *.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config -# NuGet v3's project.json files produces more ignoreable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -orleans.codegen.cs - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# Other Tooling # +.classpath +.project +target +.idea +*.iml + +# Mac OS # +.DS_Store +.DS_Store? + +# Windows # +Thumbs.db + +# reduced pom files should not be included +dependency-reduced-pom.xml \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000000..2cac09f02bfa --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: java +sudo: false +jdk: +- oraclejdk8 +script: +- mvn install -DskipTests=true +- mvn package javadoc:aggregate -DskipTests=true \ No newline at end of file diff --git a/azure-keyvault-core/pom.xml b/azure-keyvault-core/pom.xml new file mode 100755 index 000000000000..1ae87e1b1176 --- /dev/null +++ b/azure-keyvault-core/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + + com.microsoft.azure + azure-keyvault-parent + 1.0.0-beta6-SNAPSHOT + ../pom.xml + + + azure-keyvault-core + jar + + Microsoft Azure SDK for Key Vault Core + This package contains Microsoft Azure Key Vault Core SDK. + 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 + + + + + + + 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. +
*/]]>
+
+
+
+
+ + + org.apache.commons + commons-lang3 + 3.4 + + + com.google.guava + guava + 20.0 + + +
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 new file mode 100755 index 000000000000..5eb18bd42677 --- /dev/null +++ b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java @@ -0,0 +1,148 @@ +/** + * 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; + +import java.io.Closeable; +import java.security.NoSuchAlgorithmException; + +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; + +import com.google.common.util.concurrent.ListenableFuture; + + +/** + * Interface for representing cryptographic keys with the Microsoft Azure Key + * Vault libraries. + */ +public interface IKey extends Closeable { + + /** + * The default encryption algorithm for this key, using the representations + * from Json Web Key Algorithms, RFC7513. + * + * @return The default encryption algorithm for this key. + */ + String getDefaultEncryptionAlgorithm(); + + /** + * The default key wrap algorithm for this key, using the representations + * from Json Web Key Algorithms, RFC7513. + * + * @return The default key wrap algorithm for this key. + */ + String getDefaultKeyWrapAlgorithm(); + + /** + * The default signature algorithm for this key, using the representations + * from Json Web Key Algorithms, RFC7513. + * + * @return The default signature algorithm for this key. + */ + String getDefaultSignatureAlgorithm(); + + /** + * The unique key identifier for this key. + * + * @return The key identifier + */ + String getKid(); + + /** + * Decrypts the specified cipher text. Note that not all algorithms require, + * or support, all parameters. + * + * @param ciphertext + * The cipher text to decrypt + * @param iv + * The initialization vector (optional with some algorithms) + * @param authenticationData + * Additional authentication data (optional with some algorithms) + * @param authenticationTag + * The authentication tag from the encrypt operation (optional + * with some algorithms) + * @param algorithm + * The encryption algorithm to use, must be supplied + * @return A ListenableFuture containing the plain text + * @throws NoSuchAlgorithmException the algorithm is not valid + */ + ListenableFuture decryptAsync(final byte[] ciphertext, final byte[] iv, final byte[] authenticationData, final byte[] authenticationTag, final String algorithm) throws NoSuchAlgorithmException; + + /** + * Encrypts the specified plain text. Note that not all algorithms require, + * or support, all parameters. + * + * @param plaintext + * The plain text to encrypt + * @param iv + * The initialization vector (optional with some algorithms) + * @param authenticationData + * Additional authentication data (optional with some algorithms) + * @param algorithm + * The encryption algorithm to use, defaults to the keys + * DefaultEncryptionAlgorithm + * @return A ListenableFuture containing the cipher text, the authentication + * tag and the algorithm that was used + * @throws NoSuchAlgorithmException the algorithm is not valid + */ + ListenableFuture> encryptAsync(final byte[] plaintext, final byte[] iv, final byte[] authenticationData, final String algorithm) throws NoSuchAlgorithmException; + + /** + * Wraps (encrypts) the specified symmetric key material using the specified + * algorithm, or the keys DefaultKeyWrapAlgorithm if none is specified. + * + * @param key + * The symmetric key to wrap + * @param algorithm + * The wrapping algorithm to use, defaults to the keys + * DefaultKeyWrapAlgorithm + * @return ListenableFuture containing the encrypted key and the algorithm + * that was used + * @throws NoSuchAlgorithmException the algorithm is not valid + */ + ListenableFuture> wrapKeyAsync(final byte[] key, final String algorithm) throws NoSuchAlgorithmException; + + /** + * Unwraps (decrypts) the specified encryped key material. + * + * @param encryptedKey + * The encrypted key to decrypt + * @param algorithm + * The algorithm to use, must be supplied + * @return A ListenableFuture containing the unwrapped key + * @throws NoSuchAlgorithmException the algorithm is not valid + */ + ListenableFuture unwrapKeyAsync(final byte[] encryptedKey, final String algorithm) throws NoSuchAlgorithmException; + + /** + * Signs the specified digest using the specified algorithm, or the keys + * DefaultSignatureAlgorithm if no algorithm is specified. + * + * @param digest + * The digest to sign + * @param algorithm + * The signature algorithm to use + * @return A ListenableFuture containing the signature and the algorithm used. + * @throws NoSuchAlgorithmException the algorithm is not valid + */ + ListenableFuture> signAsync(final byte[] digest, final String algorithm) throws NoSuchAlgorithmException; + + /** + * Verifies the supplied signature value using the supplied digest and + * algorithm. + * + * @param digest + * The digest input + * @param signature + * The signature to verify + * @param algorithm + * The algorithm to use, must be provided + * @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-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java new file mode 100755 index 000000000000..e0b08e9ea200 --- /dev/null +++ b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java @@ -0,0 +1,40 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.core; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Interface for representing key resolving operations with the Microsoft Azure Key + * Vault libraries. + */ +public interface IKeyResolver { + + /** + * Retrieves an IKey implementation for the specified key identifier. + * Implementations should check the format of the kid to ensure that it is + * recognized. Null, rather than an exception, should be returned for + * unrecognized key identifiers to enable chaining of key resolvers. + * + * @param kid + * The key identifier to resolve. + * @return A ListenableFuture containing the resolved IKey + */ + ListenableFuture resolveKeyAsync(String kid); +} diff --git a/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/package-info.java b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/package-info.java new file mode 100755 index 000000000000..b3417f38285d --- /dev/null +++ b/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/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 the interface for IKey and IKeyResolver. + */ +package com.microsoft.azure.keyvault.core; diff --git a/azure-keyvault-cryptography/pom.xml b/azure-keyvault-cryptography/pom.xml new file mode 100755 index 000000000000..efbdba24c988 --- /dev/null +++ b/azure-keyvault-cryptography/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + + com.microsoft.azure + azure-keyvault-parent + 1.0.0-beta6-SNAPSHOT + ../pom.xml + + + azure-keyvault-cryptography + jar + + Microsoft Azure SDK for Key Vault Cryptography + This package contains Microsoft Azure SDK for Key Vault Cryptography. + 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 + + + true + + + + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk15on + test + 1.54 + + + com.microsoft.azure + azure-keyvault-core + 1.0.0-beta6-SNAPSHOT + + + com.microsoft.azure + azure-keyvault-webkey + 1.0.0-beta6-SNAPSHOT + + + 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 new file mode 100755 index 000000000000..e80ccaf5a76b --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.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.cryptography; + +/** + * Abstract base class for all Algorithm objects. + * + */ +public abstract class Algorithm { + + private final String _name; + + /** + * Constructor. + * + * @param name The name of the algorithm. + */ + protected Algorithm(String name) { + if (Strings.isNullOrWhiteSpace(name)) { + throw new IllegalArgumentException("name"); + } + + _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 new file mode 100755 index 000000000000..60930c8d1e3a --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.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.cryptography; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128CbcHmacSha256; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192Cbc; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192CbcHmacSha384; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256Cbc; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256CbcHmacSha512; +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; + +public class AlgorithmResolver { + + public static final AlgorithmResolver Default = new AlgorithmResolver(); + + static { + Default.put(Aes128CbcHmacSha256.ALGORITHM_NAME, new Aes128CbcHmacSha256()); + Default.put(Aes192CbcHmacSha384.ALGORITHM_NAME, new Aes192CbcHmacSha384()); + Default.put(Aes256CbcHmacSha512.ALGORITHM_NAME, new Aes256CbcHmacSha512()); + + Default.put(Aes128Cbc.ALGORITHM_NAME, new Aes128Cbc()); + Default.put(Aes192Cbc.ALGORITHM_NAME, new Aes192Cbc()); + Default.put(Aes256Cbc.ALGORITHM_NAME, new Aes256Cbc()); + + Default.put(AesKw128.ALGORITHM_NAME, new AesKw128()); + Default.put(AesKw192.ALGORITHM_NAME, new AesKw192()); + Default.put(AesKw256.ALGORITHM_NAME, new AesKw256()); + + Default.put(Rsa15.ALGORITHM_NAME, new Rsa15()); + Default.put(RsaOaep.ALGORITHM_NAME, new RsaOaep()); + + 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. + * + * @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); + } + + /** + * 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 new file mode 100755 index 000000000000..b239a41d8530 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java @@ -0,0 +1,86 @@ +/** + * 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.InvalidKeyException; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +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 new file mode 100755 index 000000000000..ff5e1417ba5c --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java @@ -0,0 +1,15 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.cryptography; + +public abstract class AsymmetricSignatureAlgorithm extends SignatureAlgorithm { + + protected AsymmetricSignatureAlgorithm(String name) { + super(name); + } + +} 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 000000000000..07aee9a68949 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java @@ -0,0 +1,100 @@ +/** + * 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); + } + } + + /** + * Compares two byte arrays in constant time. + * + * @param self + * The first byte array to compare + * @param other + * The second byte array to compare + * @return + * True if the two byte arrays are equal. + */ + public static boolean sequenceEqualConstantTime( byte[] self, byte[] other ) + { + if ( self == null ) + throw new IllegalArgumentException( "self" ); + + if ( other == null ) + throw new IllegalArgumentException( "other" ); + + // Constant time comparison of two byte arrays + long difference = ( self.length & 0xffffffffl ) ^ ( other.length & 0xffffffffl ); + + for ( int i = 0; i < self.length && i < other.length; i++ ) + { + difference |= ( self[i] ^ other[i] ) & 0xffffffffl; + } + + return difference == 0; + } + +} 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 new file mode 100755 index 000000000000..4d36c332b3be --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java @@ -0,0 +1,23 @@ +/** + * 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 new file mode 100755 index 000000000000..113a14404cf4 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java @@ -0,0 +1,12 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.cryptography; + +public interface IAuthenticatedCryptoTransform extends ICryptoTransform { + + public byte[] getTag(); +} 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 new file mode 100755 index 000000000000..4787a9d11a0f --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.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.cryptography; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +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 000000000000..484b1448fb51 --- /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 new file mode 100755 index 000000000000..e0028d51a507 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java @@ -0,0 +1,152 @@ +/** + * 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.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +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 new file mode 100755 index 000000000000..c8807fc29c49 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java @@ -0,0 +1,297 @@ +/** + * 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.io.IOException; +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.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; + +public class RsaKey implements IKey { + + public static int KeySize1024 = 1024; + public static int KeySize2048 = 2048; + + public static int getDefaultKeySize() { + return RsaKey.KeySize2048; + } + + 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", provider); + + generator.initialize(keySize); + + _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"); + } + + if (keyPair == null) { + throw new IllegalArgumentException("kid"); + } + + if (keyPair.getPublic() == null || !(keyPair.getPublic() instanceof RSAPublicKey)) { + throw new IllegalArgumentException("keyPair"); + } + + _kid = kid; + _keyPair = keyPair; + _provider = provider; + } + + @Override + public String getDefaultEncryptionAlgorithm() { + return RsaOaep.ALGORITHM_NAME; + } + + @Override + public String getDefaultKeyWrapAlgorithm() { + return RsaOaep.ALGORITHM_NAME; + } + + @Override + public String getDefaultSignatureAlgorithm() { + return Rs256.ALGORITHM_NAME; + } + + @Override + public String getKid() { + return _kid; + } + + @Override + public ListenableFuture decryptAsync(final byte[] ciphertext, final byte[] iv, final byte[] authenticationData, final byte[] authenticationTag, final String algorithm) throws NoSuchAlgorithmException { + + if (ciphertext == null) { + throw new IllegalArgumentException("ciphertext"); + } + + // Interpret the requested algorithm + if (Strings.isNullOrWhiteSpace(algorithm)) { + throw new IllegalArgumentException("algorithm"); + } + + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm)baseAlgorithm; + + ICryptoTransform transform; + ListenableFuture result; + + try { + transform = algo.CreateDecryptor(_keyPair, _provider); + result = Futures.immediateFuture(transform.doFinal(ciphertext)); + } catch (Exception e) { + result = Futures.immediateFailedFuture(e); + } + + return result; + } + + @Override + public ListenableFuture> encryptAsync(final byte[] plaintext, final byte[] iv, final byte[] authenticationData, final String algorithm) throws NoSuchAlgorithmException { + + if (plaintext == null) { + throw new IllegalArgumentException("plaintext"); + } + + // Interpret the requested algorithm + String algorithmName = (Strings.isNullOrWhiteSpace(algorithm) ? getDefaultEncryptionAlgorithm() : algorithm); + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { + throw new NoSuchAlgorithmException(algorithmName); + } + + AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm)baseAlgorithm; + + ICryptoTransform transform; + ListenableFuture> result; + + try { + transform = algo.CreateEncryptor(_keyPair, _provider); + result = Futures.immediateFuture(Triple.of(transform.doFinal(plaintext), (byte[]) null, algorithmName)); + } catch (Exception e) { + result = Futures.immediateFailedFuture(e); + } + + return result; + } + + @Override + public ListenableFuture> wrapKeyAsync(final byte[] key, final String algorithm) throws NoSuchAlgorithmException { + + if (key == null) { + throw new IllegalArgumentException("key"); + } + + // Interpret the requested algorithm + String algorithmName = (Strings.isNullOrWhiteSpace(algorithm) ? getDefaultKeyWrapAlgorithm() : algorithm); + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) { + throw new NoSuchAlgorithmException(algorithmName); + } + + AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm)baseAlgorithm; + + ICryptoTransform transform; + ListenableFuture> result; + + try { + transform = algo.CreateEncryptor(_keyPair, _provider); + result = Futures.immediateFuture(Pair.of(transform.doFinal(key), algorithmName)); + } catch (Exception e) { + result = Futures.immediateFailedFuture(e); + } + + return result; + } + + @Override + public ListenableFuture unwrapKeyAsync(final byte[] encryptedKey, final String algorithm) throws NoSuchAlgorithmException { + + if (encryptedKey == 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 AsymmetricEncryptionAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm)baseAlgorithm; + + ICryptoTransform transform; + ListenableFuture result; + + try { + transform = algo.CreateDecryptor(_keyPair, _provider); + result = Futures.immediateFuture(transform.doFinal(encryptedKey)); + } catch (Exception e) { + result = Futures.immediateFailedFuture(e); + } + + return result; + } + + @Override + 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) 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 + public void close() throws IOException { + // Intentionally empty + } + +} 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 new file mode 100755 index 000000000000..53d7459b9136 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java @@ -0,0 +1,15 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.cryptography; + +public abstract class SignatureAlgorithm extends Algorithm { + + protected SignatureAlgorithm(String name) { + super(name); + } + +} 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 new file mode 100755 index 000000000000..a1ead94749e6 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.keyvault.cryptography; + +public final class 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.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()) { + return true; + } + + return false; + } +} 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 new file mode 100755 index 000000000000..b582ced73492 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java @@ -0,0 +1,107 @@ +/** + * 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.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +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); + } + + /** + * 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 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 (ignored for non-authenticating algorithms) + * @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 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 (ignored for non-authenticating algorithms) + * @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 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 (ignored for non-authenticating algorithms) + * @param authenticationTag + * The authentication tag to verify when using authenticating encryption algorithms (ignored for non-authenticating algorithms) + * @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, byte[] authenticationTag) 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 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 (ignored for non-authenticating algorithms) + * @param authenticationTag + * The authentication tag to verify when using authenticating encryption algorithms (ignored for non-authenticating algorithms) + * @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, byte[] authenticationTag, 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 new file mode 100755 index 000000000000..c401d77251a8 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java @@ -0,0 +1,389 @@ +/** + * 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.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.SecureRandom; +import java.util.UUID; + +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.Aes128Cbc; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128CbcHmacSha256; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192Cbc; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192CbcHmacSha384; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256CbcHmacSha512; +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.Strings; + +/** + * A simple symmetric key implementation + * + */ +public class SymmetricKey implements IKey { + + private static final SecureRandom Rng = new SecureRandom(); + + public static final int KeySize128 = 128 >> 3; + public static final int KeySize192 = 192 >> 3; + public static final int KeySize256 = 256 >> 3; + public static final int KeySize384 = 384 >> 3; + public static final int KeySize512 = 512 >> 3; + + public static final int DefaultKeySize = KeySize256; + + private final String _kid; + private final byte[] _key; + private final Provider _provider; + + /** + * Creates a SymmetricKey with a random key identifier and + * a random key with DefaultKeySize bits. + */ + public SymmetricKey() { + this(UUID.randomUUID().toString()); + } + + /** + * Creates a SymmetricKey with the specified key identifier and + * a random key with DefaultKeySize bits. + * @param kid + * The key identifier to use. + */ + public SymmetricKey(String kid) { + this(kid, DefaultKeySize); + } + + /** + * Creates a SymmetricKey with the specified key identifier and + * a random key with the specified size. + * @param kid + * The key identifier to use. + * @param keySizeInBytes + * The key size to use in bytes. + */ + public SymmetricKey(String kid, int keySizeInBytes ) { + this(kid, keySizeInBytes, null); + } + + /** + * Creates a SymmetricKey with the specified key identifier and + * a random key with the specified size that uses the specified provider. + * @param kid + * The key identifier to use. + * @param keySizeInBytes + * The key size to use in bytes. + * @param provider + * The provider to use (optional, null for default) + */ + public SymmetricKey(String kid, int keySizeInBytes, Provider provider) { + + if ( Strings.isNullOrWhiteSpace(kid) ) { + throw new IllegalArgumentException("kid"); + } + + if ( keySizeInBytes != KeySize128 && keySizeInBytes != KeySize192 && keySizeInBytes != KeySize256 && keySizeInBytes != KeySize384 && keySizeInBytes != KeySize512 ) { + throw new IllegalArgumentException("The key material must be 128, 192, 256, 384 or 512 bits of data"); + } + + _kid = kid; + _key = new byte[keySizeInBytes]; + _provider = provider; + + // Generate a random key + Rng.nextBytes(_key); + } + + /** + * Creates a SymmetricKey with the specified key identifier and key material. + * @param kid + * The key identifier to use. + * @param keyBytes + * The key material to use. + */ + public SymmetricKey(String kid, byte[] keyBytes) { + this(kid, keyBytes, null); + } + + /** + * Creates a SymmetricKey with the specified key identifier and key material + * that uses the specified Provider. + * @param kid + * The key identifier to use. + * @param keyBytes + * The key material to use. + * @param provider + * The Provider to use (optional, null for default) + */ + public SymmetricKey(String kid, byte[] keyBytes, Provider provider) { + + if ( Strings.isNullOrWhiteSpace(kid) ) { + throw new IllegalArgumentException("kid"); + } + + if ( keyBytes == null ) { + throw new IllegalArgumentException("keyBytes"); + } + + if ( keyBytes.length != KeySize128 && keyBytes.length != KeySize192 && keyBytes.length != KeySize256 && keyBytes.length != KeySize384 && keyBytes.length != KeySize512 ) { + throw new IllegalArgumentException("The key material must be 128, 192, 256, 384 or 512 bits of data"); + } + + _kid = kid; + _key = keyBytes; + _provider = provider; + } + + @Override + public String getDefaultEncryptionAlgorithm() { + + switch (_key.length) { + case KeySize128: + return Aes128Cbc.ALGORITHM_NAME; + + case KeySize192: + return Aes192Cbc.ALGORITHM_NAME; + + case KeySize256: + return Aes128CbcHmacSha256.ALGORITHM_NAME; + + case KeySize384: + return Aes192CbcHmacSha384.ALGORITHM_NAME; + + case KeySize512: + return Aes256CbcHmacSha512.ALGORITHM_NAME; + } + + return null; + } + + @Override + public String getDefaultKeyWrapAlgorithm() { + + switch (_key.length) { + case KeySize128: + return AesKw128.ALGORITHM_NAME; + + case KeySize192: + return AesKw192.ALGORITHM_NAME; + + case KeySize256: + return AesKw256.ALGORITHM_NAME; + + case KeySize384: + // Default to longest allowed key length for wrap + return AesKw256.ALGORITHM_NAME; + + case KeySize512: + // Default to longest allowed key length for wrap + return AesKw256.ALGORITHM_NAME; + } + + return null; + } + + @Override + public String getDefaultSignatureAlgorithm() { + + return null; + } + + @Override + public String getKid() { + + return _kid; + } + + @Override + public ListenableFuture decryptAsync(final byte[] ciphertext, final byte[] iv, final byte[] authenticationData, final byte[] authenticationTag, final String algorithm) throws NoSuchAlgorithmException { + + if (Strings.isNullOrWhiteSpace(algorithm)) { + throw new IllegalArgumentException("algorithm"); + } + + if (ciphertext == null) { + throw new IllegalArgumentException("ciphertext"); + } + + if (iv == null) { + throw new IllegalArgumentException("iv"); + } + + // Interpret the algorithm + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + SymmetricEncryptionAlgorithm algo = (SymmetricEncryptionAlgorithm)baseAlgorithm; + + ICryptoTransform transform = null; + + try { + transform = algo.CreateDecryptor(_key, iv, authenticationData, authenticationTag, _provider ); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + byte[] result = null; + + try { + result = transform.doFinal(ciphertext); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + return Futures.immediateFuture(result); + } + + @Override + public ListenableFuture> encryptAsync(final byte[] plaintext, final byte[] iv, final byte[] authenticationData, final String algorithm) throws NoSuchAlgorithmException { + + if (plaintext == null) { + throw new IllegalArgumentException("plaintext"); + } + + if (iv == null) { + throw new IllegalArgumentException("iv"); + } + + // Interpret the algorithm + String algorithmName = (Strings.isNullOrWhiteSpace(algorithm)) ? getDefaultEncryptionAlgorithm() : algorithm; + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + SymmetricEncryptionAlgorithm algo = (SymmetricEncryptionAlgorithm)baseAlgorithm; + + ICryptoTransform transform = null; + + try { + transform = algo.CreateEncryptor(_key, iv, authenticationData, _provider); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + byte[] cipherText = null; + + try { + cipherText = transform.doFinal(plaintext); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + byte[] authenticationTag = null; + + if (transform instanceof IAuthenticatedCryptoTransform) { + + IAuthenticatedCryptoTransform authenticatedTransform = (IAuthenticatedCryptoTransform) transform; + + authenticationTag = authenticatedTransform.getTag().clone(); + } + + return Futures.immediateFuture(Triple.of(cipherText, authenticationTag, algorithm)); + } + + @Override + public ListenableFuture> wrapKeyAsync(final byte[] key, final String algorithm) throws NoSuchAlgorithmException { + + if (key == null || key.length == 0) { + throw new IllegalArgumentException("key"); + } + + // Interpret the algorithm + String algorithmName = (Strings.isNullOrWhiteSpace(algorithm)) ? getDefaultKeyWrapAlgorithm() : algorithm; + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof KeyWrapAlgorithm)) { + throw new NoSuchAlgorithmException(algorithmName); + } + + KeyWrapAlgorithm algo = (KeyWrapAlgorithm)baseAlgorithm; + + ICryptoTransform transform = null; + + try { + transform = algo.CreateEncryptor(_key, null, _provider); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + byte[] encrypted = null; + + try { + encrypted = transform.doFinal(key); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + return Futures.immediateFuture(Pair.of(encrypted, algorithmName)); + } + + @Override + public ListenableFuture unwrapKeyAsync(final byte[] encryptedKey, final String algorithm) throws NoSuchAlgorithmException { + + if (Strings.isNullOrWhiteSpace(algorithm)) { + throw new IllegalArgumentException("algorithm"); + } + + if (encryptedKey == null || encryptedKey.length == 0) { + throw new IllegalArgumentException("wrappedKey"); + } + + Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm); + + if (baseAlgorithm == null || !(baseAlgorithm instanceof KeyWrapAlgorithm)) { + throw new NoSuchAlgorithmException(algorithm); + } + + KeyWrapAlgorithm algo = (KeyWrapAlgorithm)baseAlgorithm; + + ICryptoTransform transform = null; + + try { + transform = algo.CreateDecryptor(_key, null, _provider); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + byte[] decrypted = null; + + try { + decrypted = transform.doFinal(encryptedKey); + } catch (Exception e) { + return Futures.immediateFailedFuture(e); + } + + return Futures.immediateFuture(decrypted); + } + + @Override + public ListenableFuture> signAsync(final byte[] digest, final String algorithm) { + return Futures.immediateFailedFuture(new NotImplementedException("signAsync is not currently supported")); + } + + @Override + public ListenableFuture verifyAsync(final byte[] digest, final byte[] signature, final String algorithm) { + return Futures.immediateFailedFuture(new NotImplementedException("verifyAsync is not currently supported")); + } + + @Override + public void close() throws IOException { + } +} 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 new file mode 100755 index 000000000000..89a10584294d --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java @@ -0,0 +1,17 @@ +/** + * 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 { + + private static final int KEY_SIZE = 128; + public static final String ALGORITHM_NAME = "A128CBC"; + + public Aes128Cbc() { + 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 new file mode 100755 index 000000000000..f473aee20d11 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.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.algorithms; + +public class Aes128CbcHmacSha256 extends AesCbcHmacSha2 { + + public static final String ALGORITHM_NAME = "A128CBC-HS256"; + + public Aes128CbcHmacSha256() { + 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 new file mode 100755 index 000000000000..fe6f3ff8f1f1 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java @@ -0,0 +1,17 @@ +/** + * 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 { + + private static final int KEY_SIZE = 192; + public static final String ALGORITHM_NAME = "A192CBC"; + + public Aes192Cbc() { + 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 new file mode 100755 index 000000000000..ecfc65f49ff6 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.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.algorithms; + +public class Aes192CbcHmacSha384 extends AesCbcHmacSha2 { + + public static final String ALGORITHM_NAME = "A192CBC-HS384"; + + public Aes192CbcHmacSha384() { + 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 new file mode 100755 index 000000000000..f198b9012b54 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java @@ -0,0 +1,17 @@ +/** + * 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 { + + private static final int KEY_SIZE = 256; + public static final String ALGORITHM_NAME = "A256CBC"; + + public Aes256Cbc() { + 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 new file mode 100755 index 000000000000..61c1aead84b7 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.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.algorithms; + +public class Aes256CbcHmacSha512 extends AesCbcHmacSha2 { + + public static final String ALGORITHM_NAME = "A256CBC-HS512"; + + public Aes256CbcHmacSha512() { + 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 new file mode 100755 index 000000000000..f2b9d28f67e3 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java @@ -0,0 +1,118 @@ +/** + * 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.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; +import com.microsoft.azure.keyvault.cryptography.SymmetricEncryptionAlgorithm; + +public abstract class AesCbc extends SymmetricEncryptionAlgorithm { + + final int keySizeInBytes; + final int keySize; + static class AesCbcDecryptor implements ICryptoTransform { + + private final Cipher _cipher; + + AesCbcDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + // Create the cipher using the Provider if specified + if (provider == null) { + _cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + } else { + _cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", provider); + } + + _cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { + return _cipher.doFinal(plaintext); + } + } + + static class AesCbcEncryptor implements ICryptoTransform { + + private final Cipher _cipher; + + AesCbcEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + // Create the cipher using the Provider if specified + if (provider == null) { + _cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + } else { + _cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", provider); + } + + _cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { + return _cipher.doFinal(plaintext); + } + } + + 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 { + + 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 { + + 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, byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + 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, byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + 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 new file mode 100755 index 000000000000..9ab0a3cd2f1e --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java @@ -0,0 +1,279 @@ +/** + * 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.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.Mac; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.lang3.tuple.Triple; + +import com.microsoft.azure.keyvault.cryptography.ByteExtensions; +import com.microsoft.azure.keyvault.cryptography.IAuthenticatedCryptoTransform; +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; +import com.microsoft.azure.keyvault.cryptography.SymmetricEncryptionAlgorithm; + +public abstract class AesCbcHmacSha2 extends SymmetricEncryptionAlgorithm { + + static class AesCbcHmacSha2Decryptor implements IAuthenticatedCryptoTransform { + + final byte[] _aad_length; + final Mac _hmac; + final byte[] _hmac_key; + final ICryptoTransform _inner; + + byte[] _tag; + + AesCbcHmacSha2Decryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + // Split the key to get the AES key, the HMAC key and the HMAC + // object + Triple parameters = GetAlgorithmParameters(name, key); + + // Save the MAC provider and key + _hmac = parameters.getRight(); + _hmac_key = parameters.getMiddle(); + + // Create the AES provider + _inner = new AesCbc.AesCbcDecryptor(parameters.getLeft(), iv, provider); + + _aad_length = toBigEndian(authenticationData.length * 8); + + // Save the tag + _tag = authenticationTag; + + // Prime the hash. + _hmac.update(authenticationData); + _hmac.update(iv); + } + + @Override + public byte[] getTag() { + return _tag; + } + + @Override + public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { + + // Add the cipher text to the running hash + _hmac.update(input); + + // Add the associated_data_length bytes to the hash + byte[] hash = _hmac.doFinal(_aad_length); + + // Compute the new tag + byte[] tag = new byte[_hmac_key.length]; + System.arraycopy(hash, 0, tag, 0, _hmac_key.length); + + // Check the tag before performing the final decrypt + if ( !ByteExtensions.sequenceEqualConstantTime(_tag, tag) ) { + throw new IllegalArgumentException("Data is not authentic"); + } + + return _inner.doFinal(input); + } + } + + static class AesCbcHmacSha2Encryptor implements IAuthenticatedCryptoTransform { + + final byte[] _aad_length; + final Mac _hmac; + final byte[] _hmac_key; + final ICryptoTransform _inner; + + byte[] _tag; + + AesCbcHmacSha2Encryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + // Split the key to get the AES key, the HMAC key and the HMAC + // object + Triple parameters = GetAlgorithmParameters(name, key); + + // Save the MAC provider and key + _hmac = parameters.getRight(); + _hmac_key = parameters.getMiddle(); + + // Create the AES encryptor + _inner = new AesCbc.AesCbcEncryptor(parameters.getLeft(), iv, provider); + + _aad_length = toBigEndian(authenticationData.length * 8); + + // Prime the hash. + _hmac.update(authenticationData); + _hmac.update(iv); + } + + @Override + public byte[] getTag() { + return _tag; + } + + // public int TransformBlock( byte[] inputBuffer, int inputOffset, int + // inputCount, byte[] outputBuffer, int outputOffset ) + // { + // // Encrypt the block + // var result = _inner.TransformBlock( inputBuffer, inputOffset, + // inputCount, outputBuffer, outputOffset ); + // + // // Add it to the running hash + // _hmac.TransformBlock( outputBuffer, outputOffset, result, + // outputBuffer, outputOffset ); + // + // return result; + // } + + @Override + public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { + + // Encrypt the block + byte[] output = _inner.doFinal(input); + + // Add the cipher text to the running hash + _hmac.update(output); + + // Add the associated_data_length bytes to the hash + byte[] hash = _hmac.doFinal(_aad_length); + + // Compute the tag + _tag = new byte[_hmac_key.length]; + System.arraycopy(hash, 0, _tag, 0, _tag.length); + + return output; + } + } + + protected AesCbcHmacSha2(String name) { + super(name); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, byte[] authenticationTag) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + return CreateDecryptor(key, iv, authenticationData, authenticationTag, null); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + if (key == null) { + throw new IllegalArgumentException("No key material"); + } + + if (iv == null) { + throw new IllegalArgumentException("No initialization vector"); + } + + if (authenticationData == null) { + throw new IllegalArgumentException("No authentication data"); + } + + if (authenticationTag == null) { + throw new IllegalArgumentException("No authentication tag"); + } + + // Create the Decryptor + return new AesCbcHmacSha2Decryptor(getName(), key, iv, authenticationData, authenticationTag, provider); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + return CreateEncryptor(key, iv, authenticationData, null); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { + + if (key == null) { + throw new IllegalArgumentException("No key material"); + } + + if (iv == null) { + throw new IllegalArgumentException("No initialization vector"); + } + + if (authenticationData == null) { + throw new IllegalArgumentException("No authentication data"); + } + + // Create the Encryptor + return new AesCbcHmacSha2Encryptor(getName(), key, iv, authenticationData, provider); + } + + private static Triple GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException { + + byte[] aes_key; + byte[] hmac_key; + Mac hmac; + + 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)); + } + + hmac_key = new byte[128 >> 3]; + aes_key = new byte[128 >> 3]; + + // The HMAC key precedes the AES key + System.arraycopy(key, 0, hmac_key, 0, 128 >> 3); + System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3); + + hmac = Mac.getInstance("HmacSHA256"); + hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); + + } 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)); + } + + hmac_key = new byte[192 >> 3]; + aes_key = new byte[192 >> 3]; + + // The HMAC key precedes the AES key + System.arraycopy(key, 0, hmac_key, 0, 192 >> 3); + System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3); + + hmac = Mac.getInstance("HmacSHA384"); + hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384")); + } 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)); + } + + hmac_key = new byte[256 >> 3]; + aes_key = new byte[256 >> 3]; + + // The HMAC key precedes the AES key + System.arraycopy(key, 0, hmac_key, 0, 256 >> 3); + System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3); + + hmac = Mac.getInstance("HmacSHA512"); + hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512")); + } else { + throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm)); + } + + return Triple.of(aes_key, hmac_key, hmac); + } + + static byte[] toBigEndian(long i) { + + byte[] shortRepresentation = BigInteger.valueOf(i).toByteArray(); + byte[] longRepresentation = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; + + System.arraycopy(shortRepresentation, 0, longRepresentation, longRepresentation.length - shortRepresentation.length, shortRepresentation.length); + + return longRepresentation; + } + +} 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 new file mode 100755 index 000000000000..6bd7dfc28c63 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java @@ -0,0 +1,180 @@ +/** + * 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.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 javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; +import com.microsoft.azure.keyvault.cryptography.KeyWrapAlgorithm; + +public abstract class AesKw extends KeyWrapAlgorithm { + + static final byte[] _defaultIv = new byte[] { (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6 }; + static final String _cipherName = "AESWrap"; + + class AesKwDecryptor implements ICryptoTransform { + + final Cipher _cipher; + + AesKwDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + if (provider == null) { + _cipher = Cipher.getInstance(_cipherName); + } else { + _cipher = Cipher.getInstance(_cipherName, provider); + } + + // The default provider does not support the specification of IV. This + // is guarded by the CreateEncrypter wrapper method and the iv parameter + // can be ignored when using the default provider + if (provider == null ) { + _cipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(key, "AES")); + } else { + _cipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); + } + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { + + return _cipher.unwrap(plaintext, "AESWrap", Cipher.SECRET_KEY).getEncoded(); + } + + } + + class AesKwEncryptor implements ICryptoTransform { + + final Cipher _cipher; + + AesKwEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + if (provider == null) { + _cipher = Cipher.getInstance(_cipherName); + } else { + _cipher = Cipher.getInstance(_cipherName, provider); + } + + // The default provider does not support the specification of IV. This + // is guarded by the CreateEncrypter wrapper method and the iv parameter + // can be ignored when using the default provider + if (provider == null ) { + _cipher.init(Cipher.WRAP_MODE, new SecretKeySpec(key, "AES")); + } else { + _cipher.init(Cipher.WRAP_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); + } + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException { + + return _cipher.wrap(new SecretKeySpec(plaintext, "AES")); + } + + } + + protected AesKw(String name) { + super(name); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + return CreateEncryptor(key, null, null); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + return CreateEncryptor(key, null, provider); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + return CreateEncryptor(key, iv, null); + } + + @Override + public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + if (key == null) { + throw new IllegalArgumentException("key"); + } + + if (key.length != 128 >> 3 && key.length != 192 >> 3 && key.length != 256 >> 3) { + throw new IllegalArgumentException("key length must be 128, 192 or 256 bits"); + } + + if (iv != null ) { + // iv length must be 64 bits + if ( iv.length != 8) { + throw new IllegalArgumentException("iv length must be 64 bits"); + } + // iv cannot be specified with the default provider + if (provider == null) { + throw new IllegalArgumentException("user specified iv is not supported with the default provider"); + } + } + + return new AesKwEncryptor(key, iv == null ? _defaultIv : iv, provider); + + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + return CreateDecryptor(key, null, null); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + return CreateDecryptor(key, null, provider); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + return CreateDecryptor(key, iv, null); + } + + @Override + public ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + + if (key == null) { + throw new IllegalArgumentException("key"); + } + + if (key.length != 128 >> 3 && key.length != 192 >> 3 && key.length != 256 >> 3) { + throw new IllegalArgumentException("key length must be 128, 192 or 256 bits"); + } + + + if (iv != null ) { + // iv length must be 64 bits + if ( iv.length != 8) { + throw new IllegalArgumentException("iv length must be 64 bits"); + } + // iv cannot be specified with the default provider + if (provider == null) { + throw new IllegalArgumentException("user specified iv is not supported with the default provider"); + } + } + + return new AesKwDecryptor(key, iv == null ? _defaultIv : iv, provider); + } + +} diff --git a/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java new file mode 100755 index 000000000000..d5696f5998f3 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java @@ -0,0 +1,57 @@ +/** + * 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.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; + +import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + +public final class AesKw128 extends AesKw { + + public static final String ALGORITHM_NAME = "A128KW"; + + static final int KeySizeInBytes = 128 >> 3; + + public AesKw128() { + super(ALGORITHM_NAME); + } + + @Override + 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 < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 128 bits long"); + } + + return super.CreateEncryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); + } + + @Override + 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 < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 128 bits long"); + } + + 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 new file mode 100755 index 000000000000..43225d8e080d --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java @@ -0,0 +1,57 @@ +/** + * 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.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; + +import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + +public final class AesKw192 extends AesKw { + + public static final String ALGORITHM_NAME = "A192KW"; + + static final int KeySizeInBytes = 192 >> 3; + + public AesKw192() { + super(ALGORITHM_NAME); + } + + @Override + 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 < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 192 bits long"); + } + + return super.CreateEncryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); + } + + @Override + 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 < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 192 bits long"); + } + + 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 new file mode 100755 index 000000000000..b2b514713c96 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java @@ -0,0 +1,57 @@ +/** + * 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.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.Arrays; + +import javax.crypto.NoSuchPaddingException; + +import com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + +public final class AesKw256 extends AesKw { + + public static final String ALGORITHM_NAME = "A256KW"; + + static final int KeySizeInBytes = 256 >> 3; + + public AesKw256() { + super(ALGORITHM_NAME); + } + + @Override + 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 < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 256 bits long"); + } + + return super.CreateEncryptor(Arrays.copyOfRange(key, 0, KeySizeInBytes), iv, provider); + } + + @Override + 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 < KeySizeInBytes) { + throw new IllegalArgumentException("key must be at least 256 bits long"); + } + + 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 000000000000..e443398bf040 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java @@ -0,0 +1,94 @@ +/** + * 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.ByteExtensions; +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 ByteExtensions.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); + } +} 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 new file mode 100755 index 000000000000..18ea8d28514f --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java @@ -0,0 +1,101 @@ +/** + * 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.security.InvalidKeyException; +import java.security.KeyPair; +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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + +public final class Rsa15 extends RsaEncryption { + + class Rsa15Decryptor implements ICryptoTransform { + + private final Cipher _cipher; + + Rsa15Decryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + + // Create a cipher object using the provider, if specified + if (provider == null) { + _cipher = Cipher.getInstance(RSA15); + } else { + _cipher = Cipher.getInstance(RSA15, provider); + } + + // encrypt the plain text using the public key + _cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { + + return _cipher.doFinal(plaintext); + } + + } + + class Rsa15Encryptor implements ICryptoTransform { + + private final Cipher _cipher; + + Rsa15Encryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + + // Create a cipher object using the provider, if specified + if (provider == null) { + _cipher = Cipher.getInstance(RSA15); + } else { + _cipher = Cipher.getInstance(RSA15, provider); + } + + // encrypt the plain text using the public key + _cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { + + return _cipher.doFinal(plaintext); + } + + } + + final static String RSA15 = "RSA/ECB/PKCS1Padding"; + + public final static String ALGORITHM_NAME = "RSA1_5"; + + public Rsa15() { + super(ALGORITHM_NAME); + } + + @Override + public ICryptoTransform CreateEncryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + return CreateEncryptor(keyPair, null); + } + + @Override + public ICryptoTransform CreateEncryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + return new Rsa15Encryptor(keyPair, provider); + } + + @Override + public ICryptoTransform CreateDecryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + return CreateDecryptor(keyPair, null); + } + + @Override + public ICryptoTransform CreateDecryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + return new Rsa15Decryptor(keyPair, provider); + } + +} 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 new file mode 100755 index 000000000000..83343057aa55 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java @@ -0,0 +1,17 @@ +/** + * 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 com.microsoft.azure.keyvault.cryptography.AsymmetricEncryptionAlgorithm; + +public abstract class RsaEncryption extends AsymmetricEncryptionAlgorithm { + + protected RsaEncryption(String name) { + super(name); + } + +} 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 new file mode 100755 index 000000000000..38c3e4131231 --- /dev/null +++ b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java @@ -0,0 +1,103 @@ +/** + * 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.security.InvalidKeyException; +import java.security.KeyPair; +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 com.microsoft.azure.keyvault.cryptography.ICryptoTransform; + +public final class RsaOaep extends RsaEncryption { + + class RsaOaepDecryptor implements ICryptoTransform { + + private final Cipher _cipher; + + RsaOaepDecryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + + // Create a cipher object using the provider, if specified + if (provider == null) { + _cipher = Cipher.getInstance(RSAOAEP); + } else { + _cipher = Cipher.getInstance(RSAOAEP, provider); + } + + // encrypt the plain text using the public key + _cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { + + return _cipher.doFinal(plaintext); + } + + } + + class RsaOaepEncryptor implements ICryptoTransform { + + private final Cipher _cipher; + + RsaOaepEncryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + + // Create a cipher object using the provider, if specified + if (provider == null) { + _cipher = Cipher.getInstance(RSAOAEP); + } else { + _cipher = Cipher.getInstance(RSAOAEP, provider); + } + + // encrypt the plain text using the public key + _cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); + } + + @Override + public byte[] doFinal(byte[] plaintext) throws IllegalBlockSizeException, BadPaddingException { + + return _cipher.doFinal(plaintext); + } + + } + + final static String RSAOAEP = "RSA/ECB/OAEPWithSHA1AndMGF1Padding"; + + public final static String ALGORITHM_NAME = "RSA-OAEP"; + + public RsaOaep() { + super(ALGORITHM_NAME); + } + + @Override + public ICryptoTransform CreateEncryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + return CreateEncryptor(keyPair, null); + } + + @Override + public ICryptoTransform CreateEncryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + + return new RsaOaepEncryptor(keyPair, provider); + } + + @Override + public ICryptoTransform CreateDecryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + return CreateDecryptor(keyPair, null); + } + + @Override + public ICryptoTransform CreateDecryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + + return new RsaOaepDecryptor(keyPair, provider); + } + +} 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 000000000000..84d2257ae217 --- /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 000000000000..f3101db3f04c --- /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/package-info.java b/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java new file mode 100644 index 000000000000..5492e8c67761 --- /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/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 new file mode 100755 index 000000000000..043b2b54808b --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java @@ -0,0 +1,18 @@ +package com.microsoft.azure.keyvault.cryptography.test; + +import java.security.Provider; + +import org.junit.Before; + +public class AesCbcBCProviderTest extends AesCbcTest { + + @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/AesCbcHmacShaBCProviderTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java new file mode 100644 index 000000000000..5c7e07a27347 --- /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 new file mode 100755 index 000000000000..ef588b4830e9 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java @@ -0,0 +1,267 @@ +package com.microsoft.azure.keyvault.cryptography.test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; + +import java.security.Provider; + +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.IAuthenticatedCryptoTransform; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128CbcHmacSha256; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192CbcHmacSha384; +import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256CbcHmacSha512; + +public class AesCbcHmacShaTest { + + 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 = null; + } + + @Test + public void testAes128CbcHmacSha256() { + // 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 + byte[] K = { (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, + (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, (byte)0x1e, (byte)0x1f }; + byte[] P = { (byte)0x41, (byte)0x20, (byte)0x63, (byte)0x69, (byte)0x70, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x20, (byte)0x73, (byte)0x79, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x6d, (byte)0x20, + (byte)0x6d, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x6e, (byte)0x6f, (byte)0x74, (byte)0x20, (byte)0x62, (byte)0x65, (byte)0x20, (byte)0x72, (byte)0x65, (byte)0x71, (byte)0x75, + (byte)0x69, (byte)0x72, (byte)0x65, (byte)0x64, (byte)0x20, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x62, (byte)0x65, (byte)0x20, (byte)0x73, (byte)0x65, (byte)0x63, (byte)0x72, (byte)0x65, + (byte)0x74, (byte)0x2c, (byte)0x20, (byte)0x61, (byte)0x6e, (byte)0x64, (byte)0x20, (byte)0x69, (byte)0x74, (byte)0x20, (byte)0x6d, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x62, + (byte)0x65, (byte)0x20, (byte)0x61, (byte)0x62, (byte)0x6c, (byte)0x65, (byte)0x20, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x66, (byte)0x61, (byte)0x6c, (byte)0x6c, (byte)0x20, (byte)0x69, + (byte)0x6e, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x68, (byte)0x61, (byte)0x6e, (byte)0x64, (byte)0x73, (byte)0x20, (byte)0x6f, (byte)0x66, + (byte)0x20, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x65, (byte)0x6e, (byte)0x65, (byte)0x6d, (byte)0x79, (byte)0x20, (byte)0x77, (byte)0x69, (byte)0x74, (byte)0x68, (byte)0x6f, + (byte)0x75, (byte)0x74, (byte)0x20, (byte)0x69, (byte)0x6e, (byte)0x63, (byte)0x6f, (byte)0x6e, (byte)0x76, (byte)0x65, (byte)0x6e, (byte)0x69, (byte)0x65, (byte)0x6e, (byte)0x63, (byte)0x65 }; + byte[] IV = { (byte)0x1a, (byte)0xf3, (byte)0x8c, (byte)0x2d, (byte)0xc2, (byte)0xb9, (byte)0x6f, (byte)0xfd, (byte)0xd8, (byte)0x66, (byte)0x94, (byte)0x09, (byte)0x23, (byte)0x41, (byte)0xbc, (byte)0x04 }; + byte[] A = { (byte)0x54, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x73, (byte)0x65, (byte)0x63, (byte)0x6f, (byte)0x6e, (byte)0x64, (byte)0x20, (byte)0x70, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x63, + (byte)0x69, (byte)0x70, (byte)0x6c, (byte)0x65, (byte)0x20, (byte)0x6f, (byte)0x66, (byte)0x20, (byte)0x41, (byte)0x75, (byte)0x67, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x20, + (byte)0x4b, (byte)0x65, (byte)0x72, (byte)0x63, (byte)0x6b, (byte)0x68, (byte)0x6f, (byte)0x66, (byte)0x66, (byte)0x73 }; + byte[] E = { (byte)0xc8, (byte)0x0e, (byte)0xdf, (byte)0xa3, (byte)0x2d, (byte)0xdf, (byte)0x39, (byte)0xd5, (byte)0xef, (byte)0x00, (byte)0xc0, (byte)0xb4, (byte)0x68, (byte)0x83, (byte)0x42, (byte)0x79, + (byte)0xa2, (byte)0xe4, (byte)0x6a, (byte)0x1b, (byte)0x80, (byte)0x49, (byte)0xf7, (byte)0x92, (byte)0xf7, (byte)0x6b, (byte)0xfe, (byte)0x54, (byte)0xb9, (byte)0x03, (byte)0xa9, (byte)0xc9, + (byte)0xa9, (byte)0x4a, (byte)0xc9, (byte)0xb4, (byte)0x7a, (byte)0xd2, (byte)0x65, (byte)0x5c, (byte)0x5f, (byte)0x10, (byte)0xf9, (byte)0xae, (byte)0xf7, (byte)0x14, (byte)0x27, (byte)0xe2, + (byte)0xfc, (byte)0x6f, (byte)0x9b, (byte)0x3f, (byte)0x39, (byte)0x9a, (byte)0x22, (byte)0x14, (byte)0x89, (byte)0xf1, (byte)0x63, (byte)0x62, (byte)0xc7, (byte)0x03, (byte)0x23, (byte)0x36, + (byte)0x09, (byte)0xd4, (byte)0x5a, (byte)0xc6, (byte)0x98, (byte)0x64, (byte)0xe3, (byte)0x32, (byte)0x1c, (byte)0xf8, (byte)0x29, (byte)0x35, (byte)0xac, (byte)0x40, (byte)0x96, (byte)0xc8, + (byte)0x6e, (byte)0x13, (byte)0x33, (byte)0x14, (byte)0xc5, (byte)0x40, (byte)0x19, (byte)0xe8, (byte)0xca, (byte)0x79, (byte)0x80, (byte)0xdf, (byte)0xa4, (byte)0xb9, (byte)0xcf, (byte)0x1b, + (byte)0x38, (byte)0x4c, (byte)0x48, (byte)0x6f, (byte)0x3a, (byte)0x54, (byte)0xc5, (byte)0x10, (byte)0x78, (byte)0x15, (byte)0x8e, (byte)0xe5, (byte)0xd7, (byte)0x9d, (byte)0xe5, (byte)0x9f, + (byte)0xbd, (byte)0x34, (byte)0xd8, (byte)0x48, (byte)0xb3, (byte)0xd6, (byte)0x95, (byte)0x50, (byte)0xa6, (byte)0x76, (byte)0x46, (byte)0x34, (byte)0x44, (byte)0x27, (byte)0xad, (byte)0xe5, + (byte)0x4b, (byte)0x88, (byte)0x51, (byte)0xff, (byte)0xb5, (byte)0x98, (byte)0xf7, (byte)0xf8, (byte)0x00, (byte)0x74, (byte)0xb9, (byte)0x47, (byte)0x3c, (byte)0x82, (byte)0xe2, (byte)0xdb }; + byte[] T = { (byte)0x65, (byte)0x2c, (byte)0x3f, (byte)0xa3, (byte)0x6b, (byte)0x0a, (byte)0x7c, (byte)0x5b, (byte)0x32, (byte)0x19, (byte)0xfa, (byte)0xb3, (byte)0xa3, (byte)0x0b, (byte)0xc1, (byte)0xc4 }; + + Aes128CbcHmacSha256 algo = new Aes128CbcHmacSha256(); + + IAuthenticatedCryptoTransform transform = null; + + byte[] encrypted = null; + byte[] tag = null; + + try { + transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(K, IV, A, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + encrypted = transform.doFinal(P); + tag = transform.getTag(); + + assertArrayEquals(E, encrypted); + assertArrayEquals(T, tag); + + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + transform = (IAuthenticatedCryptoTransform)algo.CreateDecryptor(K, IV, A, T, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = transform.doFinal(encrypted); + tag = transform.getTag(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(P, decrypted); + assertArrayEquals(T, tag); + } + + + @Test + public void testAes192CbcHmacSha384() { + // 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 + byte[] K = { (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, + (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, (byte)0x1e, (byte)0x1f, + (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, (byte)0x26, (byte)0x27, (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, (byte)0x2e, (byte)0x2f }; + byte[] P = { (byte)0x41, (byte)0x20, (byte)0x63, (byte)0x69, (byte)0x70, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x20, (byte)0x73, (byte)0x79, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x6d, (byte)0x20, + (byte)0x6d, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x6e, (byte)0x6f, (byte)0x74, (byte)0x20, (byte)0x62, (byte)0x65, (byte)0x20, (byte)0x72, (byte)0x65, (byte)0x71, (byte)0x75, + (byte)0x69, (byte)0x72, (byte)0x65, (byte)0x64, (byte)0x20, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x62, (byte)0x65, (byte)0x20, (byte)0x73, (byte)0x65, (byte)0x63, (byte)0x72, (byte)0x65, + (byte)0x74, (byte)0x2c, (byte)0x20, (byte)0x61, (byte)0x6e, (byte)0x64, (byte)0x20, (byte)0x69, (byte)0x74, (byte)0x20, (byte)0x6d, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x62, + (byte)0x65, (byte)0x20, (byte)0x61, (byte)0x62, (byte)0x6c, (byte)0x65, (byte)0x20, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x66, (byte)0x61, (byte)0x6c, (byte)0x6c, (byte)0x20, (byte)0x69, + (byte)0x6e, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x68, (byte)0x61, (byte)0x6e, (byte)0x64, (byte)0x73, (byte)0x20, (byte)0x6f, (byte)0x66, + (byte)0x20, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x65, (byte)0x6e, (byte)0x65, (byte)0x6d, (byte)0x79, (byte)0x20, (byte)0x77, (byte)0x69, (byte)0x74, (byte)0x68, (byte)0x6f, + (byte)0x75, (byte)0x74, (byte)0x20, (byte)0x69, (byte)0x6e, (byte)0x63, (byte)0x6f, (byte)0x6e, (byte)0x76, (byte)0x65, (byte)0x6e, (byte)0x69, (byte)0x65, (byte)0x6e, (byte)0x63, (byte)0x65 }; + byte[] IV = { (byte)0x1a, (byte)0xf3, (byte)0x8c, (byte)0x2d, (byte)0xc2, (byte)0xb9, (byte)0x6f, (byte)0xfd, (byte)0xd8, (byte)0x66, (byte)0x94, (byte)0x09, (byte)0x23, (byte)0x41, (byte)0xbc, (byte)0x04 }; + byte[] A = { (byte)0x54, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x73, (byte)0x65, (byte)0x63, (byte)0x6f, (byte)0x6e, (byte)0x64, (byte)0x20, (byte)0x70, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x63, + (byte)0x69, (byte)0x70, (byte)0x6c, (byte)0x65, (byte)0x20, (byte)0x6f, (byte)0x66, (byte)0x20, (byte)0x41, (byte)0x75, (byte)0x67, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x20, + (byte)0x4b, (byte)0x65, (byte)0x72, (byte)0x63, (byte)0x6b, (byte)0x68, (byte)0x6f, (byte)0x66, (byte)0x66, (byte)0x73 }; + byte[] E = { (byte)0xea, (byte)0x65, (byte)0xda, (byte)0x6b, (byte)0x59, (byte)0xe6, (byte)0x1e, (byte)0xdb, (byte)0x41, (byte)0x9b, (byte)0xe6, (byte)0x2d, (byte)0x19, (byte)0x71, (byte)0x2a, (byte)0xe5, + (byte)0xd3, (byte)0x03, (byte)0xee, (byte)0xb5, (byte)0x00, (byte)0x52, (byte)0xd0, (byte)0xdf, (byte)0xd6, (byte)0x69, (byte)0x7f, (byte)0x77, (byte)0x22, (byte)0x4c, (byte)0x8e, (byte)0xdb, + (byte)0x00, (byte)0x0d, (byte)0x27, (byte)0x9b, (byte)0xdc, (byte)0x14, (byte)0xc1, (byte)0x07, (byte)0x26, (byte)0x54, (byte)0xbd, (byte)0x30, (byte)0x94, (byte)0x42, (byte)0x30, (byte)0xc6, + (byte)0x57, (byte)0xbe, (byte)0xd4, (byte)0xca, (byte)0x0c, (byte)0x9f, (byte)0x4a, (byte)0x84, (byte)0x66, (byte)0xf2, (byte)0x2b, (byte)0x22, (byte)0x6d, (byte)0x17, (byte)0x46, (byte)0x21, + (byte)0x4b, (byte)0xf8, (byte)0xcf, (byte)0xc2, (byte)0x40, (byte)0x0a, (byte)0xdd, (byte)0x9f, (byte)0x51, (byte)0x26, (byte)0xe4, (byte)0x79, (byte)0x66, (byte)0x3f, (byte)0xc9, (byte)0x0b, + (byte)0x3b, (byte)0xed, (byte)0x78, (byte)0x7a, (byte)0x2f, (byte)0x0f, (byte)0xfc, (byte)0xbf, (byte)0x39, (byte)0x04, (byte)0xbe, (byte)0x2a, (byte)0x64, (byte)0x1d, (byte)0x5c, (byte)0x21, + (byte)0x05, (byte)0xbf, (byte)0xe5, (byte)0x91, (byte)0xba, (byte)0xe2, (byte)0x3b, (byte)0x1d, (byte)0x74, (byte)0x49, (byte)0xe5, (byte)0x32, (byte)0xee, (byte)0xf6, (byte)0x0a, (byte)0x9a, + (byte)0xc8, (byte)0xbb, (byte)0x6c, (byte)0x6b, (byte)0x01, (byte)0xd3, (byte)0x5d, (byte)0x49, (byte)0x78, (byte)0x7b, (byte)0xcd, (byte)0x57, (byte)0xef, (byte)0x48, (byte)0x49, (byte)0x27, + (byte)0xf2, (byte)0x80, (byte)0xad, (byte)0xc9, (byte)0x1a, (byte)0xc0, (byte)0xc4, (byte)0xe7, (byte)0x9c, (byte)0x7b, (byte)0x11, (byte)0xef, (byte)0xc6, (byte)0x00, (byte)0x54, (byte)0xe3 }; + byte[] T = { (byte)0x84, (byte)0x90, (byte)0xac, (byte)0x0e, (byte)0x58, (byte)0x94, (byte)0x9b, (byte)0xfe, (byte)0x51, (byte)0x87, (byte)0x5d, (byte)0x73, (byte)0x3f, (byte)0x93, (byte)0xac, (byte)0x20, + (byte)0x75, (byte)0x16, (byte)0x80, (byte)0x39, (byte)0xcc, (byte)0xc7, (byte)0x33, (byte)0xd7 }; + + Aes192CbcHmacSha384 algo = new Aes192CbcHmacSha384(); + + IAuthenticatedCryptoTransform transform = null; + + byte[] encrypted = null; + byte[] tag = null; + + try { + transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(K, IV, A, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + encrypted = transform.doFinal(P); + tag = transform.getTag(); + + assertArrayEquals(E, encrypted); + assertArrayEquals(T, tag); + + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + transform = (IAuthenticatedCryptoTransform)algo.CreateDecryptor(K, IV, A, T, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = transform.doFinal(encrypted); + tag = transform.getTag(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(P, decrypted); + assertArrayEquals(T, tag); + } + @Test + public void testAes256CbcHmacSha512() { + // 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 + byte[] K = { (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, + (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, (byte)0x1e, (byte)0x1f, + (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, (byte)0x26, (byte)0x27, (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, (byte)0x2e, (byte)0x2f, + (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37, (byte)0x38, (byte)0x39, (byte)0x3a, (byte)0x3b, (byte)0x3c, (byte)0x3d, (byte)0x3e, (byte)0x3f }; + byte[] P = { (byte)0x41, (byte)0x20, (byte)0x63, (byte)0x69, (byte)0x70, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x20, (byte)0x73, (byte)0x79, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x6d, (byte)0x20, + (byte)0x6d, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x6e, (byte)0x6f, (byte)0x74, (byte)0x20, (byte)0x62, (byte)0x65, (byte)0x20, (byte)0x72, (byte)0x65, (byte)0x71, (byte)0x75, + (byte)0x69, (byte)0x72, (byte)0x65, (byte)0x64, (byte)0x20, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x62, (byte)0x65, (byte)0x20, (byte)0x73, (byte)0x65, (byte)0x63, (byte)0x72, (byte)0x65, + (byte)0x74, (byte)0x2c, (byte)0x20, (byte)0x61, (byte)0x6e, (byte)0x64, (byte)0x20, (byte)0x69, (byte)0x74, (byte)0x20, (byte)0x6d, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x62, + (byte)0x65, (byte)0x20, (byte)0x61, (byte)0x62, (byte)0x6c, (byte)0x65, (byte)0x20, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x66, (byte)0x61, (byte)0x6c, (byte)0x6c, (byte)0x20, (byte)0x69, + (byte)0x6e, (byte)0x74, (byte)0x6f, (byte)0x20, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x68, (byte)0x61, (byte)0x6e, (byte)0x64, (byte)0x73, (byte)0x20, (byte)0x6f, (byte)0x66, + (byte)0x20, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x65, (byte)0x6e, (byte)0x65, (byte)0x6d, (byte)0x79, (byte)0x20, (byte)0x77, (byte)0x69, (byte)0x74, (byte)0x68, (byte)0x6f, + (byte)0x75, (byte)0x74, (byte)0x20, (byte)0x69, (byte)0x6e, (byte)0x63, (byte)0x6f, (byte)0x6e, (byte)0x76, (byte)0x65, (byte)0x6e, (byte)0x69, (byte)0x65, (byte)0x6e, (byte)0x63, (byte)0x65 }; + byte[] IV = { (byte)0x1a, (byte)0xf3, (byte)0x8c, (byte)0x2d, (byte)0xc2, (byte)0xb9, (byte)0x6f, (byte)0xfd, (byte)0xd8, (byte)0x66, (byte)0x94, (byte)0x09, (byte)0x23, (byte)0x41, (byte)0xbc, (byte)0x04 }; + byte[] A = { (byte)0x54, (byte)0x68, (byte)0x65, (byte)0x20, (byte)0x73, (byte)0x65, (byte)0x63, (byte)0x6f, (byte)0x6e, (byte)0x64, (byte)0x20, (byte)0x70, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x63, + (byte)0x69, (byte)0x70, (byte)0x6c, (byte)0x65, (byte)0x20, (byte)0x6f, (byte)0x66, (byte)0x20, (byte)0x41, (byte)0x75, (byte)0x67, (byte)0x75, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x20, + (byte)0x4b, (byte)0x65, (byte)0x72, (byte)0x63, (byte)0x6b, (byte)0x68, (byte)0x6f, (byte)0x66, (byte)0x66, (byte)0x73 }; + byte[] E = { (byte)0x4a, (byte)0xff, (byte)0xaa, (byte)0xad, (byte)0xb7, (byte)0x8c, (byte)0x31, (byte)0xc5, (byte)0xda, (byte)0x4b, (byte)0x1b, (byte)0x59, (byte)0x0d, (byte)0x10, (byte)0xff, (byte)0xbd, + (byte)0x3d, (byte)0xd8, (byte)0xd5, (byte)0xd3, (byte)0x02, (byte)0x42, (byte)0x35, (byte)0x26, (byte)0x91, (byte)0x2d, (byte)0xa0, (byte)0x37, (byte)0xec, (byte)0xbc, (byte)0xc7, (byte)0xbd, + (byte)0x82, (byte)0x2c, (byte)0x30, (byte)0x1d, (byte)0xd6, (byte)0x7c, (byte)0x37, (byte)0x3b, (byte)0xcc, (byte)0xb5, (byte)0x84, (byte)0xad, (byte)0x3e, (byte)0x92, (byte)0x79, (byte)0xc2, + (byte)0xe6, (byte)0xd1, (byte)0x2a, (byte)0x13, (byte)0x74, (byte)0xb7, (byte)0x7f, (byte)0x07, (byte)0x75, (byte)0x53, (byte)0xdf, (byte)0x82, (byte)0x94, (byte)0x10, (byte)0x44, (byte)0x6b, + (byte)0x36, (byte)0xeb, (byte)0xd9, (byte)0x70, (byte)0x66, (byte)0x29, (byte)0x6a, (byte)0xe6, (byte)0x42, (byte)0x7e, (byte)0xa7, (byte)0x5c, (byte)0x2e, (byte)0x08, (byte)0x46, (byte)0xa1, + (byte)0x1a, (byte)0x09, (byte)0xcc, (byte)0xf5, (byte)0x37, (byte)0x0d, (byte)0xc8, (byte)0x0b, (byte)0xfe, (byte)0xcb, (byte)0xad, (byte)0x28, (byte)0xc7, (byte)0x3f, (byte)0x09, (byte)0xb3, + (byte)0xa3, (byte)0xb7, (byte)0x5e, (byte)0x66, (byte)0x2a, (byte)0x25, (byte)0x94, (byte)0x41, (byte)0x0a, (byte)0xe4, (byte)0x96, (byte)0xb2, (byte)0xe2, (byte)0xe6, (byte)0x60, (byte)0x9e, + (byte)0x31, (byte)0xe6, (byte)0xe0, (byte)0x2c, (byte)0xc8, (byte)0x37, (byte)0xf0, (byte)0x53, (byte)0xd2, (byte)0x1f, (byte)0x37, (byte)0xff, (byte)0x4f, (byte)0x51, (byte)0x95, (byte)0x0b, + (byte)0xbe, (byte)0x26, (byte)0x38, (byte)0xd0, (byte)0x9d, (byte)0xd7, (byte)0xa4, (byte)0x93, (byte)0x09, (byte)0x30, (byte)0x80, (byte)0x6d, (byte)0x07, (byte)0x03, (byte)0xb1, (byte)0xf6 }; + byte[] T = { (byte)0x4d, (byte)0xd3, (byte)0xb4, (byte)0xc0, (byte)0x88, (byte)0xa7, (byte)0xf4, (byte)0x5c, (byte)0x21, (byte)0x68, (byte)0x39, (byte)0x64, (byte)0x5b, (byte)0x20, (byte)0x12, (byte)0xbf, + (byte)0x2e, (byte)0x62, (byte)0x69, (byte)0xa8, (byte)0xc5, (byte)0x6a, (byte)0x81, (byte)0x6d, (byte)0xbc, (byte)0x1b, (byte)0x26, (byte)0x77, (byte)0x61, (byte)0x95, (byte)0x5b, (byte)0xc5 }; + + Aes256CbcHmacSha512 algo = new Aes256CbcHmacSha512(); + + IAuthenticatedCryptoTransform transform = null; + + byte[] encrypted = null; + byte[] tag = null; + + try { + transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(K, IV, A, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + encrypted = transform.doFinal(P); + tag = transform.getTag(); + + assertArrayEquals(E, encrypted); + assertArrayEquals(T, tag); + + } catch (Exception e) { + fail(e.getMessage()); + } + + try { + transform = (IAuthenticatedCryptoTransform)algo.CreateDecryptor(K, IV, A, T, _provider); + } catch (Exception e) { + fail(e.getMessage()); + } + + byte[] decrypted = null; + + try { + decrypted = transform.doFinal(encrypted); + tag = transform.getTag(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(P, decrypted); + assertArrayEquals(T, tag); + } +} 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 100755 index 000000000000..7b41487ef988 --- /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, 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, 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, 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, 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 new file mode 100755 index 000000000000..480db6f2e896 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java @@ -0,0 +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. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import java.security.Provider; +import org.junit.Before; + +public class AesKwBCProviderTest extends AesKwTest { + + @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/AesKwTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java new file mode 100755 index 000000000000..e79e5569fe71 --- /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 000000000000..c9a9c70acaeb --- /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 new file mode 100755 index 000000000000..799827bd349c --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java @@ -0,0 +1,171 @@ +package com.microsoft.azure.keyvault.cryptography.test; + +import static org.junit.Assert.*; + +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; +import org.junit.AfterClass; +import org.junit.Before; +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 { + } + + @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 testRsa15() throws Exception { + + RsaKey key = getTestRsaKey(); + + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, Rsa15.ALGORITHM_NAME).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); + + // Assert + assertEquals(Rsa15.ALGORITHM_NAME, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); + + // 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(); + + // Assert + assertEquals(Rsa15.ALGORITHM_NAME, encrypted.getRight()); + assertArrayEquals(CEK, decrypted); + + key.close(); + } + + @Test + public void testRsaOaep() throws Exception { + + RsaKey key = getTestRsaKey(); + + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, RsaOaep.ALGORITHM_NAME).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); + + // Assert + assertEquals(RsaOaep.ALGORITHM_NAME, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); + + // 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(); + } + + @Test + public void testDefaultAlgorithm() throws Exception { + + RsaKey key = getTestRsaKey(); + + assertEquals(RsaOaep.ALGORITHM_NAME, key.getDefaultEncryptionAlgorithm()); + assertEquals(RsaOaep.ALGORITHM_NAME, key.getDefaultKeyWrapAlgorithm()); + assertEquals(Rs256.ALGORITHM_NAME, key.getDefaultSignatureAlgorithm()); + + // Wrap and Unwrap + Pair wrapped = key.wrapKeyAsync(CEK, key.getDefaultKeyWrapAlgorithm()).get(); + byte[] unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get(); + + // Assert + assertEquals(RsaOaep.ALGORITHM_NAME, wrapped.getRight()); + assertArrayEquals(CEK, unwrapped); + + // 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(); + } + + @Test + 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()); + + // Now prove we can verify the cross platform signature + result = key.verifyAsync(hash, Base64.decodeBase64(CrossPlatformSignature), "RS256").get(); + + assertTrue(result); + + key.close(); + } + + 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 new file mode 100755 index 000000000000..2954df416105 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java @@ -0,0 +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. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import java.security.Provider; +import org.junit.Before; + +public class SymmetricKeyBCProviderTest extends SymmetricKeyTest { + + @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/SymmetricKeyTest.java b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java new file mode 100644 index 000000000000..b6d3194cae05 --- /dev/null +++ b/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java @@ -0,0 +1,592 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.azure.keyvault.cryptography.test; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.concurrent.ExecutionException; + +import javax.crypto.Cipher; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.azure.keyvault.cryptography.SymmetricKey; + +public class SymmetricKeyTest { + + 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 { + setProvider(null); + } + + @After + public void tearDown() throws Exception { + } + + protected void setProvider(Provider provider) { + _provider = provider; + } + + @Test + public void testSymmetricKeyAesKw128() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; + byte[] EK = { 0x1F, (byte) 0xA6, (byte) 0x8B, 0x0A, (byte) 0x81, 0x12, (byte) 0xB4, 0x47, (byte) 0xAE, (byte) 0xF3, 0x4B, (byte) 0xD8, (byte) 0xFB, 0x5A, 0x7B, (byte) 0x82, (byte) 0x9D, 0x3E, (byte) 0x86, 0x23, 0x71, (byte) 0xD2, (byte) 0xCF, (byte) 0xE5 }; + + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A128KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyAesKw192() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; + byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; + byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B, 0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8, (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D }; + + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyAesKw256() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; + byte[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + + try { + encrypted = key.wrapKeyAsync(CEK, "A256KW").get().getLeft(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, "A256KW").get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyDefaultAlgorithmAesKw128() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; + byte[] EK = { 0x1F, (byte) 0xA6, (byte) 0x8B, 0x0A, (byte) 0x81, 0x12, (byte) 0xB4, 0x47, (byte) 0xAE, (byte) 0xF3, 0x4B, (byte) 0xD8, (byte) 0xFB, 0x5A, 0x7B, (byte) 0x82, (byte) 0x9D, 0x3E, (byte) 0x86, 0x23, 0x71, (byte) 0xD2, (byte) 0xCF, (byte) 0xE5 }; + + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + String algorithm = null; + + try { + Pair result = key.wrapKeyAsync(CEK, null).get(); + encrypted = result.getLeft(); + algorithm = result.getRight(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertEquals("A128KW", algorithm); + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, algorithm).get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyDefaultAlgorithmAesKw192() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; + byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; + byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B, 0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8, (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D }; + + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + String algorithm = null; + + try { + Pair result = key.wrapKeyAsync(CEK, null).get(); + + encrypted = result.getLeft(); + algorithm = result.getRight(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertEquals( "A192KW", algorithm); + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, algorithm).get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @Test + public void testSymmetricKeyDefaultAlgorithmAesKw256() { + // Arrange + byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; + byte[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63, (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E, 0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 }; + /* + * This test using the default JCE provider depends on whether unlimited security + * is installed or not. In the unlimited case, the full test should pass but in + * the limited case, it should fail with InvalidKeyException. + */ + boolean unlimited = hasUnlimitedCrypto(); + SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); + + byte[] encrypted = null; + String algorithm = null; + + try { + Pair result = key.wrapKeyAsync(CEK, null).get(); + encrypted = result.getLeft(); + algorithm = result.getRight(); + + if (!unlimited) fail("Expected ExecutionException"); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + // In the limited case, the failure should be InvalidKeyException + // In the unlimited case, this should not fail + if (!unlimited) { + Throwable cause = e.getCause(); + if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); + } else { + fail("ExecutionException"); + } + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + if (unlimited) { + // Assert + assertEquals("A256KW", algorithm); + assertArrayEquals(EK, encrypted); + + byte[] decrypted = null; + + try { + decrypted = key.unwrapKeyAsync(EK, algorithm).get(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(CEK, decrypted); + } + + try { + key.close(); + } catch (IOException e) { + fail("Key could not be closed"); + } + } + + @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 new file mode 100755 index 000000000000..ac865845cfed --- /dev/null +++ b/azure-keyvault-extensions/pom.xml @@ -0,0 +1,149 @@ + + + 4.0.0 + + com.microsoft.azure + azure-keyvault-parent + 1.0.0-beta6-SNAPSHOT + ../pom.xml + + + azure-keyvault-extensions + jar + + Microsoft Azure SDK for Key Vault Extensions + This package contains Microsoft Azure Key Vault SDK Extensions. + 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.microsoft.azure + azure-client-runtime + + + commons-codec + commons-codec + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk15on + test + 1.54 + + + com.microsoft.azure + azure-keyvault-core + 1.0.0-beta6-SNAPSHOT + + + com.microsoft.azure + azure-keyvault-cryptography + 1.0.0-beta6-SNAPSHOT + + + com.microsoft.azure + azure-keyvault + 1.0.0-beta6-SNAPSHOT + + + com.microsoft.azure + azure-keyvault-webkey + 1.0.0-beta6-SNAPSHOT + + + org.mockito + mockito-core + 1.10.19 + test + + + com.microsoft.azure + azure-client-authentication + test + + + com.google.guava + guava + 20.0 + + + + + + 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 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* 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-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java new file mode 100755 index 000000000000..30062e6ab527 --- /dev/null +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java @@ -0,0 +1,154 @@ +/** + * + * 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.extensions; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import com.google.common.util.concurrent.AbstractFuture; +import com.google.common.util.concurrent.ListenableFuture; +import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.core.IKeyResolver; + +/** + * The collection of key resolvers that would iterate on a key id to resolve to {@link IKey}. + */ +public class AggregateKeyResolver implements IKeyResolver { + + /** + * Future key class that resolves a key id after the async result is available. + */ + class FutureKey extends AbstractFuture { + + private final String kid; + + private boolean isCancelled = false; + private boolean isDone = false; + private IKey result = null; + + FutureKey(String kid) { + this.kid = kid; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + + // mark cancelled + isCancelled = true; + + return isCancelled; + } + + @Override + public boolean isCancelled() { + return isCancelled; + } + + @Override + public boolean isDone() { + + // always true + return isDone; + } + + @Override + public IKey get() throws InterruptedException, ExecutionException { + + // throw if cancelled + if (isCancelled) { + throw new InterruptedException(); + } + + synchronized (resolvers) { + for (IKeyResolver resolver : resolvers) { + Future futureKey = resolver.resolveKeyAsync(kid); + + result = futureKey.get(); + + if (result != null) { + break; + } + } + } + + // Mark done + isDone = true; + + return result; + } + + @Override + public IKey get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + + // throw if cancelled + if (isCancelled) { + throw new InterruptedException(); + } + + synchronized (resolvers) { + for (IKeyResolver resolver : resolvers) { + Future futureKey = resolver.resolveKeyAsync(kid); + + result = futureKey.get(timeout, unit); + + if (result != null) { + break; + } + } + } + + // Mark done + isDone = true; + + return result; + } + } + + private final List resolvers; + + /** + * Constructor. + */ + public AggregateKeyResolver() { + + resolvers = Collections.synchronizedList(new ArrayList()); + } + + /** + * Adds a key resolver to the collection of key resolvers. + * @param resolver the key resolver + */ + public void add(IKeyResolver resolver) { + + synchronized (resolvers) { + resolvers.add(resolver); + } + } + + @Override + public ListenableFuture resolveKeyAsync(String kid) { + return new FutureKey(kid); + } + +} diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java new file mode 100755 index 000000000000..f86a98b0916b --- /dev/null +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java @@ -0,0 +1,54 @@ +/** + * + * 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.extensions; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.util.concurrent.ListenableFuture; +import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.core.IKeyResolver; + +/** + * The key resolver that caches the key after resolving to {@link IKey}. + */ +public class CachingKeyResolver implements IKeyResolver { + + private final LoadingCache> cache; + + /** + * Constructor. + * @param capacity the cache size + * @param keyResolver the key resolver + */ + public CachingKeyResolver(int capacity, final IKeyResolver keyResolver) { + cache = CacheBuilder.newBuilder().maximumSize(capacity) + .build(new CacheLoader>() { + + @Override + public ListenableFuture load(String kid) { + return keyResolver.resolveKeyAsync(kid); + } }); + } + + @Override + public ListenableFuture resolveKeyAsync(String kid) { + return cache.getUnchecked(kid); + } +} 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 new file mode 100755 index 000000000000..d3bf97abc148 --- /dev/null +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java @@ -0,0 +1,245 @@ +/** + * + * 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.extensions; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; + +import com.google.common.base.Function; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +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.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; +import com.microsoft.azure.keyvault.models.KeyBundle; +import com.microsoft.azure.keyvault.models.KeyOperationResult; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; + +/** + * The key vault key that performs cryptography operations. + */ +public class KeyVaultKey implements IKey { + + /** + * Transforms the result of decrypt operation to byte array. + */ + class DecryptResultTransform implements Function { + + DecryptResultTransform() { + super(); + } + + @Override + public byte[] apply(KeyOperationResult result) { + return result.result(); + } + } + + /** + * Transforms the result of sign operation to byte array and algorithm pair. + */ + class SignResultTransform implements Function> { + + private final String algorithm; + + SignResultTransform(String algorithm) { + super(); + this.algorithm = algorithm; + } + + @Override + public Pair apply(KeyOperationResult input) { + + return Pair.of(input.result(), algorithm); + } + } + + private final KeyVaultClient client; + private IKey implementation; + + protected KeyVaultKey(KeyVaultClient client, KeyBundle keyBundle) { + + if (client == null) { + throw new IllegalArgumentException("client"); + } + + if (keyBundle == null) { + throw new IllegalArgumentException("keyBundle"); + } + + JsonWebKey key = keyBundle.key(); + + if (key == null) { + throw new IllegalArgumentException("keyBundle must contain a key"); + } + + if (key.kty().equals(JsonWebKeyType.RSA)) { + // The private key is not available for KeyVault keys + implementation = new RsaKey(key.kid(), key.toRSA(false)); + } else if (key.kty().equals(JsonWebKeyType.RSA_HSM)) { + // The private key is not available for KeyVault keys + implementation = new RsaKey(key.kid(), key.toRSA(false)); + } + + if (implementation == null) { + throw new IllegalArgumentException(String.format("The key type %s is not supported", key.kty())); + } + + this.client = client; + } + + @Override + public void close() throws IOException { + if (implementation != null) { + implementation.close(); + } + } + + @Override + public String getDefaultEncryptionAlgorithm() { + if (implementation == null) { + return null; + } + + return implementation.getDefaultEncryptionAlgorithm(); + } + + @Override + public String getDefaultKeyWrapAlgorithm() { + + if (implementation == null) { + return null; + } + + return implementation.getDefaultKeyWrapAlgorithm(); + } + + @Override + public String getDefaultSignatureAlgorithm() { + + if (implementation == null) { + return null; + } + + return implementation.getDefaultSignatureAlgorithm(); + } + + @Override + public String getKid() { + + if (implementation == null) { + return null; + } + + return implementation.getKid(); + } + + @Override + public ListenableFuture decryptAsync(byte[] ciphertext, byte[] iv, byte[] authenticationData, byte[] authenticationTag, String algorithm) { + + if (implementation == null) { + return null; + } + + if (Strings.isNullOrWhiteSpace(algorithm)) { + algorithm = getDefaultEncryptionAlgorithm(); + } + + // Never local + ListenableFuture futureCall = + client.decryptAsync( + implementation.getKid(), + new JsonWebKeyEncryptionAlgorithm(algorithm), + ciphertext, + null); + return Futures.transform(futureCall, new DecryptResultTransform()); + } + + @Override + public ListenableFuture> encryptAsync(byte[] plaintext, byte[] iv, byte[] authenticationData, String algorithm) throws NoSuchAlgorithmException { + if (implementation == null) { + return null; + } + + return implementation.encryptAsync(plaintext, iv, authenticationData, algorithm); + } + + @Override + public ListenableFuture> wrapKeyAsync(byte[] plaintext, String algorithm) throws NoSuchAlgorithmException { + if (implementation == null) { + return null; + } + + return implementation.wrapKeyAsync(plaintext, algorithm); + } + + @Override + public ListenableFuture unwrapKeyAsync(byte[] ciphertext, String algorithm) { + if (implementation == null) { + return null; + } + + if (Strings.isNullOrWhiteSpace(algorithm)) { + algorithm = getDefaultKeyWrapAlgorithm(); + } + + // Never local + ListenableFuture futureCall = + client.unwrapKeyAsync( + implementation.getKid(), + new JsonWebKeyEncryptionAlgorithm(algorithm), + ciphertext, + null); + return Futures.transform(futureCall, new DecryptResultTransform()); + } + + @Override + public ListenableFuture> signAsync(byte[] digest, String algorithm) throws NoSuchAlgorithmException { + if (implementation == null) { + return null; + } + + if (Strings.isNullOrWhiteSpace(algorithm)) { + algorithm = getDefaultSignatureAlgorithm(); + } + + // Never local + ListenableFuture futureCall = + client.signAsync( + implementation.getKid(), + new JsonWebKeySignatureAlgorithm(algorithm), + digest, + null); + return Futures.transform(futureCall, new SignResultTransform(algorithm)); + } + + @Override + public ListenableFuture verifyAsync(byte[] digest, byte[] signature, String algorithm) throws NoSuchAlgorithmException { + if (implementation == null) { + return null; + } + + return implementation.verifyAsync(digest, signature, 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 new file mode 100755 index 000000000000..7f8e778ef068 --- /dev/null +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java @@ -0,0 +1,134 @@ +/** + * + * 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.extensions; + +import java.security.Provider; +import org.apache.commons.codec.binary.Base64; + +import com.google.common.base.Function; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.microsoft.azure.keyvault.KeyIdentifier; +import com.microsoft.azure.keyvault.KeyVaultClient; +import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.core.IKeyResolver; +import com.microsoft.azure.keyvault.cryptography.SymmetricKey; +import com.microsoft.azure.keyvault.models.KeyBundle; +import com.microsoft.azure.keyvault.models.SecretBundle; + +/** + * The key resolver class that handles resolving key id to type {@link IKey} + * to be used for cryptography operations. + */ +public class KeyVaultKeyResolver implements IKeyResolver { + + static final Base64 BASE64 = new Base64(-1, null, true); + + /** + * Transforms {@link KeyBundle} to {@link IKey}. + */ + class FutureKeyFromKey implements Function { + + protected FutureKeyFromKey() { + super(); + } + + @Override + public IKey apply(KeyBundle keyBundle) { + + if (keyBundle != null) { + return new KeyVaultKey(client, keyBundle); + } + + return null; + } + } + + /** + * Transforms {@link SecretBundle} to {@link IKey}. + */ + class FutureKeyFromSecret implements Function { + + protected FutureKeyFromSecret() { + super(); + } + + @Override + public IKey apply(SecretBundle secretBundle) { + + if (secretBundle != null && secretBundle.contentType().equalsIgnoreCase("application/octet-stream")) { + byte[] keyBytes = BASE64.decode(secretBundle.value()); + + if (keyBytes != null) { + return new SymmetricKey(secretBundle.id(), keyBytes, provider); + } + } + + return null; + } + } + + private final KeyVaultClient client; + private final Provider provider; + + /** + * Constructor. + * @param client the key vault client + */ + public KeyVaultKeyResolver(KeyVaultClient client) { + this.client = client; + this.provider = null; + } + + /** + * Constructor. + * @param client the key vault client + * @param provider the java security provider + */ + public KeyVaultKeyResolver(KeyVaultClient client, Provider provider) { + this.client = client; + this.provider = provider; + } + + private ListenableFuture resolveKeyFromSecretAsync(String kid) { + + ListenableFuture futureCall = client.getSecretAsync(kid, null); + return Futures.transform(futureCall, new FutureKeyFromSecret()); + } + + private ListenableFuture resolveKeyFromKeyAsync(String kid) { + + ListenableFuture futureCall = client.getKeyAsync(kid, null); + return Futures.transform(futureCall, new FutureKeyFromKey()); + } + + @Override + public ListenableFuture resolveKeyAsync(String kid) { + + if (KeyIdentifier.isKeyIdentifier(kid)) { + return resolveKeyFromKeyAsync(kid); + } else if (SecretIdentifier.isSecretIdentifier(kid)) { + return resolveKeyFromSecretAsync(kid); + } + + return Futures.immediateFuture(null); + } + +} 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 new file mode 100755 index 000000000000..52ef356b78e3 --- /dev/null +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java @@ -0,0 +1,53 @@ +/** + * + * 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.extensions; + +/** + * String handlers. + */ +public class Strings { + + /** + * 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. + */ + public static boolean isNullOrEmpty(String arg) { + + 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 verify + * @return true if the string is empty, contains only whitespace or is null and false otherwise + */ + public static boolean isNullOrWhiteSpace(String arg) { + + if (Strings.isNullOrEmpty(arg) || arg.trim().isEmpty()) { + return true; + } + + return false; + } +} diff --git a/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html new file mode 100755 index 000000000000..12edd05fd0ba --- /dev/null +++ b/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html @@ -0,0 +1,5 @@ + + +This package contains the Azure Key Vault Extension classes. + + diff --git a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java new file mode 100755 index 000000000000..a5263c820a6d --- /dev/null +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java @@ -0,0 +1,97 @@ +/** + * + * 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.extensions.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.UncheckedExecutionException; +import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.core.IKeyResolver; +import com.microsoft.azure.keyvault.extensions.CachingKeyResolver; +import static org.mockito.Mockito.*; + +public class CachingKeyResolverTest { + + @SuppressWarnings("unchecked") + final ListenableFuture ikeyAsync = mock(ListenableFuture.class); + final static String keyId = "keyID"; + final static String keyId2 = "keyID2"; + final static String keyId3 = "keyID3"; + + + /* + * Tests the capacity limit of CachingKeyResolver by adding more keys + * than the cache limit and verifying that least recently used entity is evicted. + */ + @Test + public void KeyVault_CapacityLimitOfCachingKeyResolver() + { + IKeyResolver mockedKeyResolver = mock(IKeyResolver.class); + CachingKeyResolver resolver = new CachingKeyResolver(2, mockedKeyResolver); + + when(mockedKeyResolver.resolveKeyAsync(keyId)).thenReturn(ikeyAsync); + when(mockedKeyResolver.resolveKeyAsync(keyId2)).thenReturn(ikeyAsync); + when(mockedKeyResolver.resolveKeyAsync(keyId3)).thenReturn(ikeyAsync); + + resolver.resolveKeyAsync(keyId); + resolver.resolveKeyAsync(keyId2); + resolver.resolveKeyAsync(keyId3); + + resolver.resolveKeyAsync(keyId2); + resolver.resolveKeyAsync(keyId3); + resolver.resolveKeyAsync(keyId); + resolver.resolveKeyAsync(keyId3); + + verify(mockedKeyResolver, times(1)).resolveKeyAsync(keyId2); + verify(mockedKeyResolver, times(1)).resolveKeyAsync(keyId3); + verify(mockedKeyResolver, times(2)).resolveKeyAsync(keyId); + } + + /* + * Tests the behavior of CachingKeyResolver when resolving key throws + * and validate that the failed entity is not added to the cache. + */ + @Test + public void KeyVault_CachingKeyResolverThrows() + { + IKeyResolver mockedKeyResolver = mock(IKeyResolver.class); + CachingKeyResolver resolver = new CachingKeyResolver(10, mockedKeyResolver); + + // First throw exception and for the second call return a value + when(mockedKeyResolver.resolveKeyAsync(keyId)) + .thenThrow(new RuntimeException("test")) + .thenReturn(ikeyAsync); + + try { + resolver.resolveKeyAsync(keyId); + assertFalse("Should have thrown an exception.", true); + } + catch (UncheckedExecutionException e) { + assertTrue("RuntimeException is expected.", e.getCause() instanceof RuntimeException); + } + + resolver.resolveKeyAsync(keyId); + resolver.resolveKeyAsync(keyId); + + verify(mockedKeyResolver, times(2)).resolveKeyAsync(keyId); + } +} diff --git a/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java new file mode 100755 index 000000000000..dad23b7d49d6 --- /dev/null +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java @@ -0,0 +1,163 @@ +/** + * + * 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.extensions.test; + + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; + +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.microsoft.aad.adal4j.AuthenticationContext; +import com.microsoft.aad.adal4j.AuthenticationResult; +import com.microsoft.aad.adal4j.ClientCredential; +import com.microsoft.azure.keyvault.KeyVaultClient; +import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials; + +public class KeyVaultClientIntegrationTestBase { + + /** + * The client instance that should be used on tests. + */ + protected static KeyVaultClient keyVaultClient; + + /** + * Primary vault URI, used for keys and secrets tests. + */ + public static String getVaultUri() { + return getLiveVaultUri1(); + } + + /** + * Secondary vault URI, used to verify ability to transparently authenticate + * against a different resource. + */ + public static String getSecondaryVaultUri() { + return getLiveVaultUri2(); + } + + private static String getLiveVaultUri1() { + return getenvOrDefault("keyvault.vaulturi", "https://javasdktestvault.vault.azure.net"); + } + + private static String getLiveVaultUri2() { + return getenvOrDefault("keyvault.vaulturi.alt", "https://javasdktestvault2.vault.azure.net"); + } + + private static String getenvOrDefault(String varName, String defValue) { + String value = System.getenv(varName); + return value != null ? value : defValue; + } + + protected static void createKeyVaultClient() throws Exception { + keyVaultClient = new KeyVaultClient(createTestCredentials()); + } + + private static ServiceClientCredentials createTestCredentials() throws Exception { + return new KeyVaultCredentials() { + + @Override + public String doAuthenticate(String authorization, String resource, String scope) { + try { + AuthenticationResult authResult = getAccessToken(authorization, resource); + return authResult.getAccessToken(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + }; + } + + 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."); + } + + String clientKey = System.getenv("arm.clientkey"); + String username = System.getenv("arm.username"); + String password = System.getenv("arm.password"); + + AuthenticationResult result = null; + ExecutorService service = null; + try { + service = Executors.newFixedThreadPool(1); + AuthenticationContext context = new AuthenticationContext(authorization, false, service); + + Future future = null; + + if (clientKey != null && password == null) { + ClientCredential credentials = new ClientCredential(clientId, clientKey); + future = context.acquireToken(resource, credentials, null); + } + + if (password != null && clientKey == null) { + future = context.acquireToken(resource, clientId, username, password, null); + } + + if (future == null) { + throw new Exception("Missing or ambiguous credentials - please inform exactly one of arm.clientkey or arm.password in the environment settings."); + } + + result = future.get(); + } finally { + service.shutdown(); + } + + if (result == null) { + throw new RuntimeException("authentication result was null"); + } + return result; + } + + protected static ObjectWriter jsonWriter; + protected static ObjectReader jsonReader; + + @BeforeClass + public static void setup() throws Exception { + createKeyVaultClient(); + jsonWriter = new ObjectMapper().writer().withDefaultPrettyPrinter(); + jsonReader = new ObjectMapper().reader(); + } + + @AfterClass + public static void cleanup() throws Exception { + } + + @Before + public void beforeTest() throws Exception { + //setupTest(getClass().getSimpleName() + "-" + "??"); + } + + @After + public void afterTest() throws Exception { + //resetTest(getClass().getSimpleName() + "-" + "??"); + } + +} \ No newline at end of file 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 new file mode 100755 index 000000000000..813b4c3ee5ad --- /dev/null +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java @@ -0,0 +1,293 @@ +// +//Copyright © Microsoft Corporation, 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 +// +//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +//OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION +//ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A +//PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. +// +//See the Apache License, Version 2.0 for the specific language +//governing permissions and limitations under the License. + +package com.microsoft.azure.keyvault.extensions.test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; + +import java.security.Provider; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.apache.commons.codec.binary.Base64; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.extensions.KeyVaultKeyResolver; +import com.microsoft.azure.keyvault.models.KeyBundle; +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; + +public class KeyVaultKeyResolverBCProviderTest extends KeyVaultClientIntegrationTestBase { + + private Provider _provider = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @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) { + throw new RuntimeException(ex.getMessage()); + } + } + + @After + public void tearDown() throws Exception { + } + + private static final String KEY_NAME = "JavaExtensionKey"; + private static final String SECRET_NAME = "JavaExtensionSecret"; + + private static final Base64 _base64 = new Base64(-1, null, true); + + @Test + public void KeyVault_KeyVaultKeyResolver_Key() throws InterruptedException, ExecutionException + { + try { + // Create a key on a vault. + CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); + KeyBundle bundle = keyVaultClient.createKey(request); + + if ( bundle != null ) + { + try + { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient, _provider ); + + Future baseKeyFuture = resolver.resolveKeyAsync( bundle.keyIdentifier().baseIdentifier() ); + Future versionKeyFuture = resolver.resolveKeyAsync( bundle.keyIdentifier().identifier() ); + + IKey baseKey = baseKeyFuture.get(); + IKey versionKey = versionKeyFuture.get(); + + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + } + finally + { + // Delete the key + keyVaultClient.deleteKey( getVaultUri(), KEY_NAME ); + } + } + } + catch ( Exception ex ) + { + Assert.fail(ex.getMessage()); + } + } + + /* + * Test resolving a key from a 128bit secret encoded as base64 in a vault using various KeyVaultKeyResolver constructors. + */ + @Test + public void KeyVault_KeyVaultKeyResolver_Secret128Base64() throws InterruptedException, ExecutionException + { + // Arrange + byte[] keyBytes = { 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 }; + + try { + + SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); + + if ( secretBundle != null ) + { + try { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient ); + + IKey baseKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().identifier() ).get(); + + // Check for correct key identifiers + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + + // Ensure key operations give the expected results + byte[] encrypted = null; + + try { + encrypted = baseKey.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + + try { + encrypted = versionKey.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + finally + { + // Delete the secret + keyVaultClient.deleteSecret( getVaultUri(), SECRET_NAME ); + } + } + } + catch ( Exception ex ) { + Assert.fail(ex.getMessage()); + } + } + + /* + * Test resolving a key from a 128bit secret encoded as base64 in a vault using various KeyVaultKeyResolver constructors. + */ + @Test + public void KeyVault_KeyVaultKeyResolver_Secret192Base64() throws InterruptedException, ExecutionException + { + // Arrange + byte[] keyBytes = { 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 }; + + try { + SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); + + if ( secretBundle != null ) + { + try + { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient, _provider ); + + IKey baseKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().identifier() ).get(); + + // Check for correct key identifiers + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + + // Ensure key operations give the expected results + byte[] encrypted = null; + + try { + encrypted = baseKey.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + + try { + encrypted = versionKey.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + finally + { + // Delete the key + keyVaultClient.deleteSecret( getVaultUri(), SECRET_NAME ); + } + } + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + /* + * Test resolving a key from a 256bit secret encoded as base64 in a vault using various KeyVaultKeyResolver constructors. + */ + @Test + public void KeyVault_KeyVaultKeyResolver_Secret256Base64() throws InterruptedException, ExecutionException + { + // Arrange + byte[] keyBytes = { 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 }; + + try { + SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); + + if ( secretBundle != null ) + { + try + { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient, _provider ); + + IKey baseKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().identifier() ).get(); + + // Check for correct key identifiers + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + + // Ensure key operations give the expected results + byte[] encrypted = null; + + try { + encrypted = baseKey.wrapKeyAsync(CEK, "A256KW").get().getLeft(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + + try { + encrypted = versionKey.wrapKeyAsync(CEK, "A256KW").get().getLeft(); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + finally + { + // Delete the key + keyVaultClient.deleteSecret( getVaultUri(), SECRET_NAME ); + } + } + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + } +} 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 new file mode 100755 index 000000000000..62777c9b2610 --- /dev/null +++ b/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java @@ -0,0 +1,317 @@ +package com.microsoft.azure.keyvault.extensions.test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.concurrent.ExecutionException; +import javax.crypto.Cipher; + +import org.apache.commons.codec.binary.Base64; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.azure.keyvault.core.IKey; +import com.microsoft.azure.keyvault.extensions.KeyVaultKeyResolver; +import com.microsoft.azure.keyvault.models.KeyBundle; +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 +// +//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 +// +//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +//OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION +//ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A +//PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. +// +//See the Apache License, Version 2.0 for the specific language +//governing permissions and limitations under the License. + +public class KeyVaultKeyResolverDefaultProviderTest extends KeyVaultClientIntegrationTestBase { + + 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 { + } + + private static final boolean _unlimited = hasUnlimitedCrypto(); + + + private static final String KEY_NAME = "JavaExtensionKey"; + private static final String SECRET_NAME = "JavaExtensionSecret"; + + private static final Base64 _base64 = new Base64(-1, null, true); + + @Test + public void KeyVault_KeyVaultKeyResolver_Key() throws InterruptedException, ExecutionException + { + try { + // Create a key on a vault. + CreateKeyRequest request = new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build(); + KeyBundle keyBundle = keyVaultClient.createKey(request); + + try + { + // ctor with client + final KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient ); + + IKey baseKey = resolver.resolveKeyAsync( keyBundle.keyIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( keyBundle.keyIdentifier().identifier() ).get(); + + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + } + finally + { + // Delete the key + keyVaultClient.deleteKey( getVaultUri(), KEY_NAME ); + } + } catch(Exception ex) { + fail(ex.getMessage()); + } + } + + /* + * Test resolving a key from a 128bit secret encoded as base64 in a vault using various KeyVaultKeyResolver constructors. + */ + @Test + public void KeyVault_KeyVaultKeyResolver_Secret128Base64() throws InterruptedException, ExecutionException + { + // Arrange + byte[] keyBytes = { 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 }; + + try { + SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); + SecretBundle secretBundle = keyVaultClient.setSecret(request); + + if ( secretBundle != null ) + { + try + { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient ); + + IKey baseKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().identifier() ).get(); + + // Check for correct key identifiers + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + + // Ensure key operations give the expected results + byte[] encrypted = null; + + try { + encrypted = baseKey.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + + try { + encrypted = versionKey.wrapKeyAsync(CEK, "A128KW").get().getLeft(); + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + finally + { + // Delete the key + keyVaultClient.deleteSecret( getVaultUri(), SECRET_NAME ); + } + } + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + } + + /* + * Test resolving a key from a 128bit secret encoded as base64 in a vault using various KeyVaultKeyResolver constructors. + */ + @Test + public void KeyVault_KeyVaultKeyResolver_Secret192Base64() throws InterruptedException, ExecutionException + { + // Arrange + byte[] keyBytes = { 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 }; + + try { + SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); + + if ( secretBundle != null ) + { + try + { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient ); + + IKey baseKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().identifier() ).get(); + + // Check for correct key identifiers + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + + // Ensure key operations give the expected results + byte[] encrypted = null; + + try { + encrypted = baseKey.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + + if (!_unlimited) fail("Expected ExecutionException"); + } 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 ( Exception ex ) { + fail(ex.getMessage()); + } + + if ( _unlimited ) { + // Assert + assertArrayEquals(EK, encrypted); + + try { + encrypted = versionKey.wrapKeyAsync(CEK, "A192KW").get().getLeft(); + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + } + finally + { + // Delete the key + keyVaultClient.deleteSecret( getVaultUri(), SECRET_NAME ); + } + } + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + } + + /* + * Test resolving a key from a 256bit secret encoded as base64 in a vault using various KeyVaultKeyResolver constructors. + */ + @Test + public void KeyVault_KeyVaultKeyResolver_Secret256Base64() throws InterruptedException, ExecutionException + { + // Arrange + byte[] keyBytes = { 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 }; + + try { + SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); + SecretBundle secretBundle = keyVaultClient.setSecret( request ); + + if ( secretBundle != null ) + { + try + { + // ctor with client + KeyVaultKeyResolver resolver = new KeyVaultKeyResolver( keyVaultClient ); + + IKey baseKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().baseIdentifier() ).get(); + IKey versionKey = resolver.resolveKeyAsync( secretBundle.secretIdentifier().identifier() ).get(); + + // Check for correct key identifiers + Assert.assertEquals( baseKey.getKid(), versionKey.getKid() ); + + // Ensure key operations give the expected results + byte[] encrypted = null; + + try { + encrypted = baseKey.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); + + try { + encrypted = versionKey.wrapKeyAsync(CEK, "A256KW").get().getLeft(); + } catch (InterruptedException e) { + fail("InterrupedException"); + } catch (ExecutionException e) { + fail("ExecutionException"); + } catch (NoSuchAlgorithmException e) { + fail("NoSuchAlgorithmException"); + } + + // Assert + assertArrayEquals(EK, encrypted); + } + } + finally + { + // Delete the key + keyVaultClient.deleteSecret( getVaultUri(), SECRET_NAME ); + } + } + } catch ( Exception ex ) { + fail(ex.getMessage()); + } + } +} diff --git a/azure-keyvault-webkey/pom.xml b/azure-keyvault-webkey/pom.xml new file mode 100644 index 000000000000..f39ebfeff52a --- /dev/null +++ b/azure-keyvault-webkey/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + + com.microsoft.azure + azure-keyvault-parent + 1.0.0-beta6-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 + + + com.google.guava + guava + 20.0 + + + + + junit + junit + test + + + + + + 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 000000000000..9418b15a9673 --- /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 000000000000..eac3d33e26c7 --- /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-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java new file mode 100755 index 000000000000..4e6ad1fd67d9 --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java @@ -0,0 +1,813 @@ +/** + * 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 java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.PublicKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.security.spec.RSAPrivateKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.google.common.base.Objects; + +/** + * 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. + */ + private String kid; + + /** + * Key type, usually RSA. Possible values include: 'EC', 'RSA', 'RSA-HSM', + * 'oct'. + */ + private JsonWebKeyType kty; + + /** + * The keyOps property. + */ + private List keyOps; + + /** + * RSA modulus. + */ + private byte[] n; + + /** + * RSA public exponent. + */ + private byte[] e; + + /** + * RSA private exponent. + */ + private byte[] d; + + /** + * RSA Private Key Parameter. + */ + private byte[] dp; + + /** + * RSA Private Key Parameter. + */ + private byte[] dq; + + /** + * RSA Private Key Parameter. + */ + private byte[] qi; + + /** + * RSA secret prime. + */ + private byte[] p; + + /** + * RSA secret prime, with p < q. + */ + private byte[] q; + + /** + * Symmetric key. + */ + private byte[] k; + + /** + * HSM Token, used with Bring Your Own Key. + */ + private byte[] t; + + /** + * Key Identifier. + * + * @return the kid value. + */ + @JsonProperty("kid") + public String kid() { + return this.kid; + } + + /** + * Set the key identifier value. + * + * @param kid the key identifier + * @return the JsonWebKey object itself. + */ + public JsonWebKey withKid(String kid) { + this.kid = kid; + return this; + } + + /** + * Key type, usually RSA. Possible values include: 'EC', 'RSA', 'RSA-HSM', + * 'oct'. + * + * @return the key type. + */ + @JsonProperty("kty") + public JsonWebKeyType kty() { + return this.kty; + } + + /** + * Set the key type value. + * + * @param kty the key type + * @return the JsonWebKey object itself. + */ + public JsonWebKey withKty(JsonWebKeyType kty) { + this.kty = kty; + return this; + } + + /** + * Get the key operations. + * + * @return the key operations. + */ + @JsonProperty("key_ops") + public List keyOps() { + return this.keyOps; + } + + /** + * Set the key operations value. + * + * @param keyOps the key operations value to set + * @return the JsonWebKey object itself. + */ + public JsonWebKey withKeyOps(List keyOps) { + this.keyOps = keyOps; + return this; + } + + /** + * Get the RSA modulus value. + * + * @return the RSA modulus value. + */ + @JsonProperty("n") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) + public byte[] n() { + return this.n; + } + + /** + * Set the RSA modulus value. + * + * @param n the RSA modulus value to set + * @return the JsonWebKey object itself. + */ + public JsonWebKey withN(byte[] n) { + this.n = n; + return this; + } + + /** + * 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() { + return this.e; + } + + /** + * Set the RSA public exponent value. + * + * @param e RSA public exponent value to set + * @return the JsonWebKey object itself. + */ + public JsonWebKey withE(byte[] e) { + this.e = e; + return this; + } + + /** + * 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() { + return this.d; + } + + /** + * Set RSA private exponent value. + * + * @param d the RSA private exponent value to set. + * @return the JsonWebKey object itself. + */ + public JsonWebKey withD(byte[] d) { + this.d = d; + return this; + } + + /** + * 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() { + return this.dp; + } + + /** + * 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) { + this.dp = dp; + return this; + } + + /** + * 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() { + return this.dq; + } + + /** + * 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) { + this.dq = dq; + return this; + } + + /** + * 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() { + return this.qi; + } + + /** + * 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) { + this.qi = qi; + return this; + } + + /** + * 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() { + return this.p; + } + + /** + * Set the RSA secret prime value. + * @param p the RSA secret prime value. + * @return the JsonWebKey object itself. + */ + public JsonWebKey withP(byte[] p) { + this.p = p; + return this; + } + + /** + * 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() { + return this.q; + } + + /** + * 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) { + this.q = q; + return this; + } + + /** + * Get Symmetric key value. + * @return the symmetric key value. + */ + @JsonProperty("k") + @JsonSerialize(using = Base64UrlJsonSerializer.class) + @JsonDeserialize(using = Base64UrlJsonDeserializer.class) + public byte[] k() { + return this.k; + } + + /** + * Set the Symmetric key value. + * @param k the symmetric key value to set. + * @return the JsonWebKey object itself. + */ + public JsonWebKey withK(byte[] k) { + this.k = k; + return this; + } + + /** + * 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() { + return this.t; + } + + /** + * 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) { + this.t = t; + return this; + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + /** + * Get the RSA public key spec value. + * + * @return the RSA public key spec value + */ + private RSAPublicKeySpec getRSAPublicKeySpec() { + + return new RSAPublicKeySpec(toBigInteger(n), toBigInteger(e)); + } + + /** + * Get the RSA private key spec value. + * + * @return the RSA private key spec value + */ + private RSAPrivateKeySpec getRSAPrivateKeySpec() { + + return new RSAPrivateCrtKeySpec(toBigInteger(n), toBigInteger(e), toBigInteger(d), toBigInteger(p), + toBigInteger(q), toBigInteger(dp), toBigInteger(dq), toBigInteger(qi)); + } + + /** + * Get the RSA public key value. + * + * @param provider the Java security provider. + * @return the RSA public key value + */ + private PublicKey getRSAPublicKey(Provider provider) { + + try { + RSAPublicKeySpec publicKeySpec = getRSAPublicKeySpec(); + KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA"); + + return factory.generatePublic(publicKeySpec); + } catch (GeneralSecurityException e) { + throw new IllegalStateException(e); + } + } + + /** + * Get the RSA private key value. + * + * @param provider the Java security provider. + * @return the RSA private key value + */ + private PrivateKey getRSAPrivateKey(Provider provider) { + + try { + RSAPrivateKeySpec privateKeySpec = getRSAPrivateKeySpec(); + KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA"); + + return factory.generatePrivate(privateKeySpec); + } catch (GeneralSecurityException e) { + throw new IllegalStateException(e); + } + } + + /** + * Verifies if the key is an RSA key. + */ + private void checkRSACompatible() { + if (!JsonWebKeyType.RSA.equals(kty) && !JsonWebKeyType.RSA_HSM.equals(kty)) { + throw new UnsupportedOperationException("Not an RSA key"); + } + } + + private static byte[] toByteArray(BigInteger n) { + byte[] result = n.toByteArray(); + if (result[0] == 0) { + // The leading zero is used to let the number positive. Since RSA + // parameters are always positive, we remove it. + return Arrays.copyOfRange(result, 1, result.length); + } + return result; + } + + private static BigInteger toBigInteger(byte[] b) { + if (b[0] < 0) { + // RSA parameters are always positive numbers, so if the first byte + // is negative, we need to add a leading zero + // to make the entire BigInteger positive. + byte[] temp = new byte[1 + b.length]; + System.arraycopy(b, 0, temp, 1, b.length); + b = temp; + } + return new BigInteger(b); + } + + /** + * Converts RSA key pair to JSON web key. + * @param keyPair RSA key pair + * @return the JSON web key, converted from RSA key pair. + */ + public static JsonWebKey fromRSA(KeyPair keyPair) { + + RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate(); + JsonWebKey key = null; + + if (privateKey != null) { + + key = new JsonWebKey() + .withKty(JsonWebKeyType.RSA) + .withN(toByteArray(privateKey.getModulus())) + .withE(toByteArray(privateKey.getPublicExponent())) + .withD(toByteArray(privateKey.getPrivateExponent())) + .withP(toByteArray(privateKey.getPrimeP())) + .withQ(toByteArray(privateKey.getPrimeQ())) + .withDp(toByteArray(privateKey.getPrimeExponentP())) + .withDq(toByteArray(privateKey.getPrimeExponentQ())) + .withQi(toByteArray(privateKey.getCrtCoefficient())); + } else { + + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + + key = new JsonWebKey() + .withKty(JsonWebKeyType.RSA) + .withN(toByteArray(publicKey.getModulus())) + .withE(toByteArray(publicKey.getPublicExponent())) + .withD(null) + .withP(null) + .withQ(null) + .withDp(null) + .withDq(null) + .withQi(null); + } + + return key; + } + + /** + * Converts JSON web key to RSA key pair. + * @return RSA key pair + */ + public KeyPair toRSA() { + return this.toRSA(false); + } + + /** + * Converts JSON web key to RSA key pair and include the private key if set to true. + * @param includePrivateParameters true if the RSA key pair should include the private key. False otherwise. + * @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(provider), getRSAPrivateKey(provider)); + } else { + return new KeyPair(getRSAPublicKey(provider), null); + } + } + + /** + * Converts AES key to JSON web key. + * @param secretKey AES key + * @return the JSON web key, converted from AES key. + */ + public static JsonWebKey fromAes(SecretKey secretKey) { + if (secretKey == null) { + return null; + } + + return new JsonWebKey() + .withK(secretKey.getEncoded()) + .withKty(JsonWebKeyType.OCT); + } + + /** + * Converts JSON web key to AES key. + * @return AES key + */ + public SecretKey toAes() { + if (k == null) { + return null; + } + + SecretKey secretKey = new SecretKeySpec(k, "AES"); + return secretKey; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof JsonWebKey) { + return this.equals((JsonWebKey) obj); + } + return super.equals(obj); + } + + /** + * Indicates whether some other {@link JsonWebKey} is "equal to" this one. + * @param jwk the other {@link JsonWebKey} to compare with. + * @return true if this {@link JsonWebKey} is the same as the jwk argument; false otherwise. + */ + public boolean equals(JsonWebKey jwk) { + if (jwk == null) { + return false; + } + + if (!Objects.equal(kid, jwk.kid)) { + return false; + } + + if (!Objects.equal(kty, jwk.kty)) { + return false; + } + + if (!Objects.equal(keyOps, jwk.keyOps)) { + return false; + } + + if (!Arrays.equals(k, jwk.k)) { + return false; + } + + // Public parameters + if (!Arrays.equals(n, jwk.n)) { + return false; + } + if (!Arrays.equals(e, jwk.e)) { + return false; + } + + // Private parameters + if (!Arrays.equals(d, jwk.d)) { + return false; + } + if (!Arrays.equals(dp, jwk.dp)) { + return false; + } + if (!Arrays.equals(dq, jwk.dq)) { + return false; + } + if (!Arrays.equals(qi, jwk.qi)) { + return false; + } + if (!Arrays.equals(p, jwk.p)) { + return false; + } + if (!Arrays.equals(q, jwk.q)) { + return false; + } + + // HSM token + if (!Arrays.equals(t, jwk.t)) { + return false; + } + + return true; + } + + /** + * Verifies whether the {@link JsonWebKey} has private key. + * @return true if the {@link JsonWebKey} has private key; false otherwise. + */ + public boolean hasPrivateKey() { + + if (JsonWebKeyType.OCT.equals(kty)) { + return k != null; + } + + else if (JsonWebKeyType.RSA.equals(kty) || JsonWebKeyType.RSA_HSM.equals(kty)) { + return (d != null && dp != null && dq != null && qi != null && p != null && q != null); + } + + return false; + } + + /** + * Verifies whether the {@link JsonWebKey} is valid. + * @return true if the {@link JsonWebKey} is valid; false otherwise. + */ + @JsonIgnore + public boolean isValid() { + if (kty == null) { + return false; + } + + if (keyOps != null) { + final Set set = new HashSet(JsonWebKeyOperation.ALL_OPERATIONS); + for (int i = 0; i < keyOps.size(); i++) { + if (!set.contains(keyOps.get(i))) { + return false; + } + } + } + + if (JsonWebKeyType.OCT.equals(kty)) { + return isValidOctet(); + } + + else if (JsonWebKeyType.RSA.equals(kty)) { + return isValidRsa(); + } + + else if (JsonWebKeyType.RSA_HSM.equals(kty)) { + return isValidRsaHsm(); + } + return false; + } + + private boolean isValidOctet() { + if (k != null) { + return true; + } + return false; + } + + private boolean isValidRsa() { + if (n == null || e == null) { + return false; + } + + return hasPrivateKey() + || (d == null && dp == null && dq == null && qi == null && p == null && q == null); + } + + private boolean isValidRsaHsm() { + // MAY have public key parameters + if ((n == null && e != null) || (n != null && e == null)) { + return false; + } + + // no private key + if (hasPrivateKey()) { + return false; + } + + // MUST have ( T || ( N && E ) ) + boolean tokenParameters = t != null; + boolean publicParameters = (n != null && e != null); + + if (tokenParameters && publicParameters) { + return false; + } + + return (tokenParameters || publicParameters); + } + + /** + * Clear key materials. + */ + public void clearMemory() { + zeroArray(k); k = null; + zeroArray(n); n = null; + zeroArray(e); e = null; + zeroArray(d); d = null; + zeroArray(dp); dp = null; + zeroArray(dq); dq = null; + zeroArray(qi); qi = null; + zeroArray(p); p = null; + zeroArray(q); q = null; + zeroArray(t); t = null; + } + + private static void zeroArray(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + @Override + public int hashCode() { + int hashCode = 48313; // setting it to a random prime number + if (kid != null) { + hashCode += kid.hashCode(); + } + + if (JsonWebKeyType.OCT.equals(kty)) { + hashCode += hashCode(k); + } + + else if (JsonWebKeyType.RSA.equals(kty)) { + hashCode += hashCode(n); + } + + else if (JsonWebKeyType.RSA_HSM.equals(kty)) { + hashCode += hashCode(t); + } + + return hashCode; + } + + private static int hashCode(byte[] obj) { + int hashCode = 0; + + if (obj == null || obj.length == 0) { + return 0; + } + + for (int i = 0; i < obj.length; i++) { + hashCode = (hashCode << 3) | (hashCode >> 29) ^ obj[i]; + } + return hashCode; + } +} \ 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 000000000000..67e5e99dd08c --- /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 000000000000..9dbb9d30fce6 --- /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 000000000000..5e532c10cd29 --- /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 000000000000..8a7c9dbffbc8 --- /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-webkey/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 new file mode 100755 index 000000000000..6768bb504520 --- /dev/null +++ b/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java @@ -0,0 +1,8 @@ +// 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 the classes for key vault JSON web key. + */ +package com.microsoft.azure.keyvault.webkey; diff --git a/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java new file mode 100644 index 000000000000..3d1ed2b07c77 --- /dev/null +++ b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java @@ -0,0 +1,92 @@ +package com.microsoft.azure.keyvault.webkey.test; + +import java.util.Arrays; +import java.util.Random; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; + +import org.junit.Assert; +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; + +public class AesValidationTests { + private static final String TRANSFORMATION = "AES"; + + @Test + public void aesKeyValidation() throws Exception { + KeyGenerator keyGen = KeyGenerator.getInstance(TRANSFORMATION); + keyGen.init(256); + + SecretKey skey = keyGen.generateKey(); + JsonWebKey key = serializeDeserialize(skey); + Assert.assertTrue(key.hasPrivateKey()); + Assert.assertTrue(key.isValid()); + + SecretKey secretKey = key.toAes(); + encryptDecrypt(secretKey); + + // Compare equal JSON web keys + JsonWebKey sameKey = JsonWebKey.fromAes(skey); + Assert.assertEquals(key, key); + Assert.assertEquals(key, sameKey); + Assert.assertEquals(key.hashCode(), sameKey.hashCode()); + } + + @Test + public void invalidKeyOps() throws Exception { + JsonWebKey key = getAes(); + key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, new JsonWebKeyOperation("foo"))); + Assert.assertFalse(key.isValid()); + } + + @Test + public void octHashCode() throws Exception { + JsonWebKey key = getAes(); + + // Compare hash codes for unequal JWK that would not map to the same hash + Assert.assertNotEquals(key.hashCode(), new JsonWebKey().withK(key.k()).hashCode()); + Assert.assertNotEquals(key.hashCode(), new JsonWebKey().withKty(key.kty()).hashCode()); + + // Compare hash codes for unequal JWK that would map to the same hash + Assert.assertEquals(key.hashCode(), new JsonWebKey().withK(key.k()).withKty(key.kty()).hashCode()); + } + + private static JsonWebKey getAes() throws Exception { + KeyGenerator keyGen = KeyGenerator.getInstance(TRANSFORMATION); + keyGen.init(256); + + SecretKey skey = keyGen.generateKey(); + return JsonWebKey.fromAes(skey); + } + + private static JsonWebKey serializeDeserialize(SecretKey skey) throws Exception { + JsonWebKey webKey = JsonWebKey.fromAes(skey); + String serializedKey = webKey.toString(); + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(serializedKey, JsonWebKey.class); + } + + private static void encryptDecrypt(SecretKey key) throws Exception { + byte[] plaintext = new byte[10]; + new Random().nextBytes(plaintext); + byte[] cipherText = encrypt(key, plaintext); + Assert.assertArrayEquals(decrypt(key, cipherText), plaintext); + } + + private static byte[] encrypt(SecretKey key, byte[] plaintext) throws Exception { + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(plaintext); + } + + private static byte[] decrypt(SecretKey key, byte[] ciphertext) throws Exception { + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(ciphertext); + } +} diff --git a/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java new file mode 100644 index 000000000000..f28801584059 --- /dev/null +++ b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java @@ -0,0 +1,56 @@ +package com.microsoft.azure.keyvault.webkey.test; + +import java.util.Random; + +import org.junit.Assert; +import org.junit.Test; + +import com.microsoft.azure.keyvault.webkey.JsonWebKey; + +public class ClearMemoryTests { + + @Test + public void clearMemory() + { + JsonWebKey key = new JsonWebKey() + .withD(getRandomByte()) + .withDp(getRandomByte()) + .withDq(getRandomByte()) + .withE(getRandomByte()) + .withK(getRandomByte()) + .withN(getRandomByte()) + .withP(getRandomByte()) + .withQ(getRandomByte()) + .withQi(getRandomByte()) + .withT(getRandomByte()); + key.clearMemory(); + Assert.assertNull(key.d()); + Assert.assertNull(key.dp()); + Assert.assertNull(key.dq()); + Assert.assertNull(key.e()); + Assert.assertNull(key.k()); + Assert.assertNull(key.n()); + Assert.assertNull(key.p()); + Assert.assertNull(key.q()); + Assert.assertNull(key.qi()); + Assert.assertNull(key.t()); + + // Compare it with a newly created JsonWebKey with no properties set. + JsonWebKey key2 = new JsonWebKey(); + Assert.assertTrue(key2.equals(key)); + } + + @Test + public void clearNullMemory() + { + JsonWebKey key = new JsonWebKey(); + key.clearMemory(); + } + + private static byte[] getRandomByte() { + byte[] bytes = new byte[10]; + new Random().nextBytes(bytes); + return bytes; + } + +} diff --git a/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java new file mode 100644 index 000000000000..816db50104ae --- /dev/null +++ b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java @@ -0,0 +1,45 @@ +package com.microsoft.azure.keyvault.webkey.test; + +import org.junit.Assert; +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; + +public class RsaHsmValidationTests { + + String keyWithoutT = "{\"kid\":\"key_id\",\"kty\":\"RSA-HSM\",\"key_ops\":[\"encrypt\",\"decrypt\"],\"n\":\"1_6ZtP288hEkKML-L6nFyZh1PD1rmAgwbbwjEvTSDK_008BYWhjp_6ULy9BhWtRIytNkPkm9gzaBTrCpp-vyDXPGa836Htp-w8u5JmxoUZchJh576m3m-8ZYWTmZSAp5SpruyKAmLSxPJHEWPXQntnmuTMjb9HBT9Ltrwc0ZDk-jsMLYunDJrNmrRUxQgb0zQ_Tl5fJjj8j-0KVx2RXtbfWFvf5fRdBYyP3m0aUpoopQPwtXszD2LcSKMJ_TnmnvMWr8MOA5aRlBaGdBk7zBgRafvDPam3Q2AvFA9mfcAVncpfZ3JFm73VARw6MofXtRqOHtZ7y4oNbY95xXwU2r6w\",\"e\":\"AQAB\"}"; + String keyWithT = "{\"kid\":\"key_id\",\"kty\":\"RSA-HSM\",\"key_ops\":[\"encrypt\",\"decrypt\"],\"key_hsm\":\"T-TOKEN\"}"; + + @Test + public void rsaHsmValidation() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + JsonWebKey keyNoT = mapper.readValue(keyWithoutT, JsonWebKey.class); + JsonWebKey keyT = mapper.readValue(keyWithT, JsonWebKey.class); + + Assert.assertTrue(keyNoT.isValid()); + Assert.assertFalse(keyNoT.hasPrivateKey()); + + Assert.assertTrue(keyT.isValid()); + Assert.assertFalse(keyT.hasPrivateKey()); + } + + @Test + public void rsaHsmHashCode() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + JsonWebKey keyNoT = mapper.readValue(keyWithoutT, JsonWebKey.class); + JsonWebKey keyT = mapper.readValue(keyWithT, JsonWebKey.class); + + Assert.assertNotEquals(keyT.hashCode(), keyNoT.hashCode()); + + // Compare hash codes for unequal JWK that would not map to the same hash + Assert.assertNotEquals(keyT.hashCode(), new JsonWebKey().withKid(keyT.kid()).withT(keyT.t()).hashCode()); + Assert.assertNotEquals(keyT.hashCode(), new JsonWebKey().withKid(keyT.kid()).withKty(keyT.kty()).hashCode()); + Assert.assertNotEquals(keyNoT.hashCode(), new JsonWebKey().hashCode()); + + // Compare hash codes for unequal JWK that would map to the same hash + Assert.assertEquals(keyT.hashCode(), + new JsonWebKey().withKid(keyT.kid()).withKty(keyT.kty()).withT(keyT.t()).hashCode()); + Assert.assertEquals(keyNoT.hashCode(), new JsonWebKey().withKid(keyT.kid()).hashCode()); + } +} diff --git a/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java new file mode 100644 index 000000000000..cb5bcb3de228 --- /dev/null +++ b/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java @@ -0,0 +1,126 @@ +package com.microsoft.azure.keyvault.webkey.test; + +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.ArrayList; +import java.util.Map; +import java.util.Random; + +import javax.crypto.Cipher; + +import org.junit.Assert; +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; + +public class RsaValidationTests { + + private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding"; + + @Test + public void rsaPublicKeyValidation() throws Exception { + for(String keyStr : keys.values()) + { + ObjectMapper mapper = new ObjectMapper(); + JsonWebKey key = mapper.readValue(keyStr, JsonWebKey.class); + Assert.assertTrue(key.hasPrivateKey()); + Assert.assertTrue(key.isValid()); + + KeyPair keyPair = key.toRSA(); + validateRsaKey(keyPair, key); + Assert.assertNull(keyPair.getPrivate()); + + // Compare equal JSON web keys + JsonWebKey sameKey = mapper.readValue(keyStr, JsonWebKey.class); + Assert.assertEquals(key, key); + Assert.assertEquals(key, sameKey); + Assert.assertEquals(key.hashCode(), sameKey.hashCode()); + } + } + + @Test + public void rsaPrivateKeyValidation() throws Exception { + for(String keyStr : keys.values()) + { + ObjectMapper mapper = new ObjectMapper(); + JsonWebKey key = mapper.readValue(keyStr, JsonWebKey.class); + + KeyPair keyPairWithPrivate = key.toRSA(true); + validateRsaKey(keyPairWithPrivate, key); + encryptDecrypt(keyPairWithPrivate.getPublic(), keyPairWithPrivate.getPrivate()); + } + } + + @Test + public void rsaHashCode() throws Exception { + + String keyStr = (String) keys.values().toArray()[0]; + ObjectMapper mapper = new ObjectMapper(); + JsonWebKey key = mapper.readValue(keyStr, JsonWebKey.class); + + // Compare hash codes for unequal JWK that would not map to the same hash + Assert.assertNotEquals(key.hashCode(), new JsonWebKey().withKid(key.kid()).withN(key.n()).hashCode()); + Assert.assertNotEquals(key.hashCode(), new JsonWebKey().withKid(key.kid()).withKty(key.kty()).hashCode()); + Assert.assertNotEquals(key.hashCode(), new JsonWebKey().withKid(key.kid()).withT(key.t()).hashCode()); + + // Compare hash codes for unequal JWK that would map to the same hash + Assert.assertEquals(key.hashCode(), + new JsonWebKey().withN(key.n()).withKty(key.kty()).withKid(key.kid()).hashCode()); + } + + private static void encryptDecrypt(PublicKey publicKey, PrivateKey privateKey) throws Exception { + byte[] plaintext = new byte[10]; + new Random().nextBytes(plaintext); + byte[] cipherText = encrypt(publicKey, plaintext); + if(privateKey != null) { + Assert.assertArrayEquals(decrypt(privateKey, cipherText), plaintext); + } + } + + private static byte[] encrypt(PublicKey key, byte[] plaintext) throws Exception { + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(plaintext); + } + + private static byte[] decrypt(PrivateKey key, byte[] ciphertext) throws Exception { + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(ciphertext); + } + + private static void validateRsaKey(KeyPair keyPair, JsonWebKey key) throws Exception { + JsonWebKey jsonWebKey = JsonWebKey.fromRSA(keyPair); + boolean includePrivateKey = keyPair.getPrivate() != null; + KeyPair keyPair2 = jsonWebKey.toRSA(includePrivateKey); + + Assert.assertTrue(includePrivateKey == jsonWebKey.hasPrivateKey()); + + PublicKey publicKey = keyPair2.getPublic(); + PrivateKey privateKey = keyPair2.getPrivate(); + + if(includePrivateKey) { + Assert.assertNotNull(privateKey); + + // set the missing properties to compare the keys + jsonWebKey.withKeyOps(new ArrayList(key.keyOps())); + jsonWebKey.withKid(new String(key.kid())); + Assert.assertEquals(jsonWebKey, key); + Assert.assertEquals(key.hashCode(), jsonWebKey.hashCode()); + } + + encryptDecrypt(publicKey, privateKey); + } + + Map keys = ImmutableMap.builder() + .put(512, "{\"kty\":\"RSA\",\"n\":\"uOXIpiH9L0h_byTuP3fcMvKbfS85eTKvxW2skw4oIU2TM3ceFvlDwDK4gKHl4qE4z18bz0qrv9ElstOrT96piQ\",\"e\":\"AQAB\",\"d\":\"And2KMA5uQ1r9MwuvZCODi0D2lcFvz7oBbenyxqmuhTYfdGcuGE9FZg5V6ZcNwBK_eYGZqSwL1Gh2EmzG6AxwQ\",\"dp\":\"CEh8kzQnCRK97NKQeV_wGgWsLYlmgis7Cms85_DIqwE\",\"dq\":\"TAi0G0iE5pvMpiEN2y189hjSRSqE6Unc1lXaE3hcnWE\",\"qi\":\"2HhNqW3QBv1R_iEpu44KVMQs0DdnY5oWp1lH6hgPhXU\",\"p\":\"5BblSoMJmO5Afa-urQFzFpBfACt1175NMUs4tHUYEkE\",\"q\":\"z4Xdf_FU-51wTkW5mFJ6QoDK-GrkMXSdct9hdW26NUk\",\"key_ops\":[\"wrapKey\",\"unwrapKey\",\"encrypt\",\"decrypt\",\"sign\",\"verify\"],\"kid\":\"key_id\"}") + .put(1024, "{\"kty\":\"RSA\",\"n\":\"zicSNMeAUYwp6V6UQlJ8gW04o6O4ZJBIefsLnV6-to1YkzgDu6vDBWb83DcDgB2x63W-ZVK23F4dcJcULu1VM-jX83Sfg0b_ZrugiiXCnZ4iidLNcY5QOS1dSHjfI1eWH6QdLPSIE3sHk-BILrIXqoyIJH-LFxzMu--4bDlej2M\",\"e\":\"AQAB\",\"d\":\"A4h7F2YT6bhG2TXcJ9OiFQj6LFPLmG2gnSnGssiQHDDWXWLB-mvT-9O4CBr2ETJxFvsw0cVV8CqGXQrTaodGxOuCGNmYoczodvlhUBJyMBxAI2or5eZUF9jRiECvigoxNVWKsqWxypvq_X1pMfQbh9ot7F6KOJAEg6wlLTc-fIE\",\"dp\":\"v2JbDaZfi3OCCLMtNMjOxfNsBOPb1IqerGux4IR17fLIzG6JlcyaR4uasILdjE4VufqnppZ6FIlFCZUiyIP0GQ\",\"dq\":\"m6NTbNOxN2qnont_qttyqg6WvOA6zWK55-ZnX8hShmlv0ySgtw1PfOWso3wpRMHAujTOfUSeI14DgOLHLNkKtQ\",\"qi\":\"HOcBZfyxW1dSnghCvdTuKL3jLSww6k_v0jhYET32gyKe8od7uxP7w0dXZ8al4zQ3xGxrip9y7jJi0pjG-Z4uGw\",\"p\":\"6dlyTUBrwxLyLbr0X3yqmNu3VrHSt2zbW8jueZFWXPELlbuQ6EKrHoR39BM8MSjFN5PfZbsBhcqNBkqhitj6xw\",\"q\":\"4a4DOrnZt4423myMKmhgDINvIdNmLCHG0aE8UWcSPKO6RFhzHX46NJSoOuk9gvccMKEXOpcJC6P8b8ypN-OKhQ\",\"key_ops\":[\"wrapKey\",\"unwrapKey\",\"encrypt\",\"decrypt\",\"sign\",\"verify\"],\"kid\":\"key_id\"}") + .put(2048, "{\"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\",\"key_ops\":[\"wrapKey\",\"unwrapKey\",\"encrypt\",\"decrypt\",\"sign\",\"verify\"],\"kid\":\"key_id\"}") + .put(3072, "{\"kty\":\"RSA\",\"n\":\"03u6K67VN18OzIRZdvCC8F9iOVojF-0kk03JQ7rfwumQMqgxLYOmLkrqLcyJV69XYt32LeEesuwuz_zJbQo9gg4T1pnKJSb-l5xoH1rfnihdc9PyMAH___d_zv3Zg9vdusg668eO1oqS5DtAe517suzwhcMIyCsFNx4aBxCDiPlEwzYISwMQHylt-4d6mbFsqJoGK14WqxTOyv0mLoeeDPs9gmQulGbyjYdZJgqjeRBMuHpXgjs_eMwHuqYmWr-jmbRMzBJpKoAgAJkDxkJzJ7wdf4Bq9HrutVspXqw9ZWh4ImIq65Rm5Mx3JDlUNdlYB0jMyDHpuwAZfr8shACty2d5bvlMnk7aYKngCbX2ZSm6BFInA4mz1eey9Iz8uxnfyEjwaYJCFRDy44P_8aymW4tsLoLYgWnF9NodxcLVbhJjBqsipYiUbvW6PUUB4SVtql4yI3EEcZsFFVAVOnms1sXGXK8vm9V9KU1RSWqF268jMD8s-QHg3a1WmooX6sw5\",\"e\":\"AQAB\",\"d\":\"WKU3m6DcmamcK-jcEUluMTBiHTUlmZ1a4-3Ki7vUmEBLo5gxiOjyatwW_dyKwzjpkbUFQCTpN8ldM-w7SBvvPUkGUsFC5MDMHaO_V0lBi2tTBL6V-T6VXmcRaSOpnaY28liErhkHS_Fo8gbOGCKiW5UKmp7uWu0BciGJemWXJP6LLqJC5qJhixZUFgcrQioHKELrjBkTumFt7tMewokxHDLhjPrONYFTcTSHDzWNYS0OY5NQg_OuvsUTBk8nq4lA2GSQqXyM-B2gbwG6pLSwccwu0x3Fd8qurxg6TSGQAjh69Iyb9ZwiHMsx3XLV95Jmqc0rcEbCzLZUBxX3daGjshw3Yd3pzEXqM8Mz-58p835VPhSMlZB_yvtP72o2QiKybhq1ob5Ygt7hqlqe08K5StN2rzJJoFkwivhfC3_KDX7XSLEK9PzqPaTOkkJu7y7tJgi6aC6Fq-X3fgeLy20LsBKV_SF4Zd323IZ713iGJFJo0f4mDUXfQmU3wrILk40L\",\"dp\":\"V5SlApD1a0ng5XrzEmOV2EVKVLcS7Z2j1WYLVa4BMxSsi8zJal_v8nllEN8ylDTWKCZt6Dg3fcHtOWKYGe7e2fBMwSsKcjPI2aFVHjI18ZMbC1m6eHWK81zlTQ-ZhgiRMXQvsRCX6Qt8PPvqfV4j-YILYfgJbQ_DRYEfJzq9JCQjFwGUiSoZvOBl9jQMM1u4NmOnvodwf8Jk4Oi1DC65U-CjOC7D07eDPNv74Pog6h6x3u7Z9S-ITvP1NX4h0_ot\",\"dq\":\"rg2IrHzp59w8nZbtd4NDk_stRB8xT6T2pxpH3LhNhEbLrmy0sF4Xemm8frlgRWeEn9dUV2nzveorEJF57bZ3cclEqBGtD72y_IRPZTPgDcYhc9l4xKJkJJuA3yWcQ6eHZHjLAZHi9PszYvFiUx1veHU2S_f7aGKjO14n05wb9r-YUmIKt7AVwK94HksflvNIREa867E2OL1lIJiX3azkyMgTnSHvi0bwgdIGp6uPdDwVW_qvvUmlFinDWflgq58\",\"qi\":\"Dw0f0UwU2KN98stNeuk2UVtG-GyKjCxSSYocGBlShsXzxeLn2faLSkkqhUVicW4o2PmedPDpxanDW2Gl7osamaPb25CodPS3JJxeHWrJ6hGBfKqvJnysZ-0zL8wVzwuNLc3VL-jlCudFfGK03MBapA9h3qjAFFhHZRgLH8y64MimARfh2gLldZ0FgNF9zB4yxmVzvpOng4XRJGzSBKdf9QbuL60Tia2rWR7QU2GtbrXlp4KiNZspZuzmBLZPaa82\",\"p\":\"3lnk-l3lG3ahUzPzhInjwTJEDRrAt0YMhpLmO444TNs0MD__RxRQO8EAhLGCuKaNJmKOg-D5-Fup34KBAcFKw1vCh06PNxoIbHmcY1KwrlA3M_47pK74sK532429sM2N0JH9ti4QjtcD85__THeS6I5g8x8xdSH6sm6ubOiUWUQ96fN10pDv-9D7PuoHGEGlndvsRE0GwWmBIjCnIbxXN4kQsE5YXbrY_WTdPXxwTb8F6Cqc2WXIuhZLlSqd8NjD\",\"q\":\"83zNQcd3dTEpO-j6e7hHeKYghVBhIViD6bXDzD3IX--maTnllGMD-xxHNzOURwl_VzwWo1Al_QQSKDMeEnNDXhSU50qbdhdyVDyRXQuR2Fb9hN5SACX-SiPgfs-2buJVZh8JD-VFSI7ou6eMQ9h-uIGnhoxH3vCs7dJgy-mHGPsvqTypaIo3LHGfM21z8h0yqgyYwaanv5UllaustjvRFId_2oWqNtrn6q410s9W5-6Q6xqkrW2m_lUffu7ViRdT\",\"key_ops\":[\"wrapKey\",\"unwrapKey\",\"encrypt\",\"decrypt\",\"sign\",\"verify\"],\"kid\":\"key_id\"}") + .put(4096, "{\"kty\":\"RSA\",\"n\":\"mmpRerSZYY4Xx_s89Qn3NMAmJOW0TXtddwjdTedA2CITP_BQW9Q6K7ZEKcAk5W8KwfvAYEIDkWN0iKtoSiBmTJxgCqpDI2MO1D_JJXFP6Tovbtgj1FJ8Ai90w04wmxoCdS9mFC2tE51qUWO7frJpTGrZqVAB8UMH031c3pUPzWedGRvKwj7J-Awtg_IoByaK-qoyRlwfqm8WpHjg6R6Fn1aJY3Fp62l1F3XGayUgqoJmg0_YzYxKpz9WDqIJo15sbyQEpTG6kRybD8T5O8908JU2d3KPp7GOKDNpai5wdaK50QyvaU3BtvKI35IaK367FSVPEZPEoAGgUBCoLXx8N16XHVgjspSMV6NnjBEoehr4xU3nw4cZ-09yZSXJv5FGKmg4pkJGCHQwUfA3XlWNZSPYIgBByyjpMe6gJt_RDBhkkYGVddkwn4HPlMIk3Gi9wzMLuVcLNVeq5k4Us3YsaXdSPI6LSfoosu7mi8qm2JMYlFzbB9_FaxJWqgHlTRSiXX0XNuHPMJoBHtKwh_7VXxiosim8EvszF_Is1ttF77l5lC198slQ5zsZ2XM90Ln9UV04kAyI1jEegDiW37uVSikt-VKyVKSZg5lgmp16CevLnqD2g_YD6fJMmbU4QmeVELhZeQc7Z_XGH7lM1bSeiAJ0dKlDKDURnA0h2LQfquM\",\"e\":\"AQAB\",\"d\":\"D_CvEz5WzGihW9Y7p1qtV5deWKtoaXc1YXcGIWdLR68nfY-OkWw0dRQOWqD92LwVyDX3g02ilfzw_WAfFp0xnPGnmHJAbAQVy83_MwuiIYQNfCEj0bnnbfJS2LaBngFEBQTXl3hU8ulqcuxwtoDZuIxvMQ3pUBaIqvRjWeGEDW2Hch1vA45ScHYRXMWVYZJBAToAkUgr8f7LFOoa4vXGUCSGxOqNnJejrBWkXfsp3BrfVOmGipwo42BOae71lRUc7HwzXo-Q9YSWcpJK3Y8U60umoRNacQfgkkB8aVGnRP1_YRfbeRYQdpT4PDFrh4Hq83aJKwSuD4vGGNMfXqgIdSWhREajFDN653gDIIrt1BPh-snE9HIr0QWJmGQTlKTFfXMEoHx6mxJgUmzZSdQ9BkfCYyInpevh2piUrdpoAEEBapYyTmEHetutMm6cpPd4EK7-yHf3f1k1Rx-HIkiN-pLPiy6x6sRS-272pRNJUjEyRr7QIxgv2rVmQpFd3HZIsmTA9e5HnEH88pbwzqckWeA8nCpe6vr9uJ5MkIMaZq1Exw2bL8TjezbQdRvFm6eO25ECBE_YRuTm72hWfkn1Aocz5_RrSvW6gjwXpgTB6ScNyDrrmo9Kz8DQA7uvRvwhS48fceGGqEt_02qtj_FY1e8Q-XLVsPz-oafqbrTPI0E\",\"dp\":\"D9PGN8qEoUjBFIDKfuilcKwpU25pLnGsgnlzXxORZYB2T1y_DzHVXoSFkcOcFfn2L-AWFSUQmFlt37ULSoSTi2J5KzeydzXfkz4CauzqyEEyv1Uu_FBM6ZDb14ZkYoS8B_vWx7ow99fopwwObs5LH9vtGmiAJczVTNuwUQd_8uRXsWdoy2Ku8XLmNBaxvpXjzbs3ooKIw450PWB1qk455OrQ0k2dqrbY5VlOjgBEk317yCamGbPy2AgC4EnXnAZ0qJ5gN-mJNbjBCjkS0MImMWphJCrXkKMxl1OURKW_ujb7B5EGXcTmJuFxu8uE6_SxDrhmbCfdrwnfVdQXIGyGsw\",\"dq\":\"xEmqiGWKIuuyMX3wElvw2E_qJfuJ58lyAqQOYrM8ROsk4iaV9yc9G57pHsLRdiCYYrYDoisi96LdJ6kScAcS8j5TAuAdHq2riI0MOd-lZr6I4S_3pnjO3SuHYmCoFagnpIo7QM9-l2ZguDrfCjs7PtQZqMWSg-ncHYrHDsbynhe9GPdes01u4XZ3Y2xoYBDJX2iCXVNKJBUeYwlLd01p4eE1O_UkI8GdxQDMOr0ifOjWa9HtmY13Q8yvWoDtA4UX9Ec83mB3F2RWi4b-0C1pxSifCzeo4VZ0uOZ_aR4ZKfx7npWseE6F-Ue2vPx3qnfZQAkXaqJPsR15ZU0ZtJqAEQ\",\"qi\":\"fzpgNvwBpXBjLkqVkKnGD20kTR1lnMfXKJHk_iGE3UY7FVRSGXiUWpRWo-Gh0Lq8jJVXddX3looqv-v_9uKHja2JkHToWSkJajRznFHvz1pMfs7d3Nr4puumuNxJC1rgktnOIK4eikNxxHJ5Rs6TeQOwWxRbmywMiEeUQAwVvgaaF91g8FmNUE4C2BCpav-1fKkr_ydo1j4AgcSaCcKuywPBvp2Fznf4UcND_1vyZVKhSBbqbu6ql8vb9zEo3E8AKsrn9REji0BnA5kHk1Ps7GiQcMSCdazwBq1kw3DYD5Mt4CuyOdg6Btg-MVDXLLS0Dw0VEvcPhi7ypUlpl0RWcQ\",\"p\":\"uFaIjld13k5EkpQtTJ6zw9Zq5QJwaVBu1RiyXTdji8ysU6rxk07HAsUt049BuKqFv2jdKVDsdL25WkIao93hstdl8Kl_7XQX491_1np1hW-NvapNUYo5UUn-SeT4zseoIu8n-GarEAI00U8Xj2M4pewd82zlCQHTCXZiwbWGF2XMfPqvpYhFtEoMyJUf8z6qCvcZgp-neJJNbLgesspHke8--GwYN-QjrUynkmUGZ14BQdnLsmNLeaWY7A92sLSOFYVK8XnXSzOUld2P5JCgTenS5Na5UpuaY1K8od8rci3TE23Gtma5VhqBiPOFgPXmlkpkBe1uRn84iV5avYQfdw\",\"q\":\"1nHaNzR3mE6cyzPqsqNxT_FDDzMXHCmxW8cO_9GzmFBW6MhNArPEIV9BFAo-NRjDKMYKPin67MlyiLCMN-TWTayeNeuvw_WYwKfI_t9xuyf1nsW-TsNoK4n2d0kwoB5OEH9pAtQKv9rSZl4WULePldJBF4lPBhQb0lmRu-HB_SRskZe8CdDcm-gjwLhoP76gstWN5PNzgrPTpxBC6tHdWD-ZbkzIGWzCjxNHAnJkUAEsy3FVllCtO4pMVXz3zupaVzmDlUQ34weWXqkA-C7QgUPNoCD_M7PTNJKQpnTwlgk1Jvn8v4FDrpmYvv5l8B9swMPtlIi9xADuuEg8gO5i9Q\",\"key_ops\":[\"wrapKey\",\"unwrapKey\",\"encrypt\",\"decrypt\",\"sign\",\"verify\"],\"kid\":\"key_id\"}") + .build(); +} diff --git a/azure-keyvault/pom.xml b/azure-keyvault/pom.xml new file mode 100755 index 000000000000..66bad0f465a2 --- /dev/null +++ b/azure-keyvault/pom.xml @@ -0,0 +1,116 @@ + + + 4.0.0 + + com.microsoft.azure + azure-keyvault-parent + 1.0.0-beta6-SNAPSHOT + ../pom.xml + + + azure-keyvault + jar + + Microsoft Azure SDK for Key Vault + This package contains Microsoft Azure Key Vault SDK. + 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.microsoft.azure + azure-client-runtime + + + com.microsoft.azure + azure-keyvault-webkey + 1.0.0-beta6-SNAPSHOT + + + + + junit + junit + test + + + com.microsoft.azure + azure-client-authentication + test + + + + + + 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/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java new file mode 100755 index 000000000000..c78460edcfde --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java @@ -0,0 +1,49 @@ +/** + * 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; + +/** + * The certificate identifier. + */ +public final class CertificateIdentifier extends ObjectIdentifier { + + /** + * Verify whether the identifier is for certificate. + * @param identifier the certificate identifier + * @return true if the identifier is the certificate identifier. False otherwise. + */ + public static boolean isCertificateIdentifier(String identifier) { + return ObjectIdentifier.isObjectIdentifier("certificates", identifier); + } + + /** + * Constructor. + * @param vault The vault url + * @param name the certificate name + */ + public CertificateIdentifier(String vault, String name) { + this(vault, name, ""); + } + + /** + * Constructor. + * @param vault the vault url + * @param name the certificate name + * @param version the certificate version + */ + public CertificateIdentifier(String vault, String name, String version) { + super(vault, "certificates", name, version); + } + + /** + * Constructor. + * @param identifier the certificate identifier + */ + public CertificateIdentifier(String identifier) { + super("certificates", identifier); + } +} 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 new file mode 100755 index 000000000000..ed88be41ab01 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.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; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * The certificate operation identifier. + */ +public final class CertificateOperationIdentifier extends ObjectIdentifier { + + /** + * Verifies whether the identifier belongs to a key vault certificate operation. + * @param identifier the key vault certificate operation identifier. + * @return true if the identifier belongs to a key vault certificate operation. False otherwise. + */ + public static boolean isCertificateOperationIdentifier(String identifier) { + identifier = verifyNonEmpty(identifier, "identifier"); + + URI baseUri; + try { + baseUri = new URI(identifier); + } catch (URISyntaxException e) { + return false; + } + + // Path is of the form "/certificates/[name]/pending" + String[] segments = baseUri.getPath().split("/"); + if (segments.length != 4) { + return false; + } + + if (!(segments[1]).equals("certificates")) { + return false; + } + + if (!(segments[3]).equals("pending")) { + return false; + } + + return true; + } + + /** + * Constructor. + * @param vault the vault url + * @param name the name of certificate + * @param version the certificate version + */ + public CertificateOperationIdentifier(String vault, String name, String version) { + super(vault, "certificates", name, "pending"); + } + + /** + * Constructor. + * @param identifier the key vault certificate operation identifier. + */ + public CertificateOperationIdentifier(String identifier) { + super("certificates", identifier); + if (!version().equals("pending")) { + throw new IllegalArgumentException( + String.format("Invalid CertificateOperationIdentifier: {0}", identifier)); + } + } +} 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 new file mode 100755 index 000000000000..6d50e9c6c049 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java @@ -0,0 +1,106 @@ +/** + * 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; + +import java.net.URI; +import java.net.URISyntaxException; +import java.security.InvalidParameterException; + +/** + * The issuer identifier. + */ +public final class IssuerIdentifier extends ObjectIdentifier { + + /** + * Verifies whether the identifier belongs to a key vault issuer. + * @param identifier the key vault issuer identifier. + * @return true if the identifier belongs to a key vault issuer. False otherwise. + */ + public static boolean isIssuerIdentifier(String identifier) { + identifier = verifyNonEmpty(identifier, "identifier"); + + URI baseUri; + try { + baseUri = new URI(identifier); + } catch (URISyntaxException e) { + return false; + } + + String[] segments = baseUri.getPath().split("/"); + if (segments.length != 4 || segments[1] != "certificates" || segments[2] != "issuers") { + return false; + } + + return true; + } + + /** + * Constructor. + * @param vault the vault url. + * @param name the name of issuer. + */ + public IssuerIdentifier(String vault, String name) { + vault = verifyNonEmpty(vault, "vault"); + + name = verifyNonEmpty(name, "name"); + + URI baseUri; + try { + baseUri = new URI(vault); + } catch (URISyntaxException e) { + throw new InvalidParameterException(String.format("Invalid ObjectIdentifier: %s. Not a valid URI", vault)); + } + + this.name = name; + this.version = null; + this.vault = String.format("%s://%s", baseUri.getScheme(), getFullAuthority(baseUri)); + + baseIdentifier = String.format("%s/%s/%s", this.vault, "certificates/issuers", this.name); + identifier = baseIdentifier; + } + + /** + * Constructor. + * @param identifier the key vault issuer identifier. + */ + public IssuerIdentifier(String identifier) { + + identifier = verifyNonEmpty(identifier, "identifier"); + + URI baseUri; + try { + baseUri = new URI(identifier); + } catch (URISyntaxException e) { + throw new InvalidParameterException( + String.format("Invalid ObjectIdentifier: %s. Not a valid URI", identifier)); + } + + // Path is of the form "/collection/name[/version]" + String[] segments = baseUri.getPath().split("/"); + if (segments.length != 4) { + throw new InvalidParameterException(String + .format("Invalid ObjectIdentifier: %s. Bad number of segments: %d", identifier, segments.length)); + } + + if (!segments[1].equals("certificates")) { + throw new InvalidParameterException( + String.format("Invalid ObjectIdentifier: %s. Segment [1] should be '%s', found '%s'", identifier, + "certificates", segments[1])); + } + if (!segments[2].equals("issuers")) { + throw new InvalidParameterException( + String.format("Invalid ObjectIdentifier: %s. Segment [2] should be '%s', found '%s'", identifier, + "issuers", segments[2])); + } + + name = segments[3]; + version = ""; + vault = String.format("%s://%s", baseUri.getScheme(), getFullAuthority(baseUri)); + baseIdentifier = String.format("%s/%s/%s", vault, "certificates/issuers", name); + this.identifier = baseIdentifier; + } +} 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 new file mode 100755 index 000000000000..67dcd6f35b83 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java @@ -0,0 +1,49 @@ +/** + * 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; + +/** + * The Key Vault key identifier. + */ +public final class KeyIdentifier extends ObjectIdentifier { + + /** + * Verifies whether the identifier belongs to a key vault key. + * @param identifier the key vault key identifier. + * @return true if the identifier belongs to a key vault key. False otherwise. + */ + public static boolean isKeyIdentifier(String identifier) { + return ObjectIdentifier.isObjectIdentifier("keys", identifier); + } + + /** + * Constructor. + * @param vault the vault url. + * @param name the name of key. + */ + public KeyIdentifier(String vault, String name) { + this(vault, name, ""); + } + + /** + * Constructor. + * @param vault the vault url. + * @param name the name of key. + * @param version the key version. + */ + public KeyIdentifier(String vault, String name, String version) { + super(vault, "keys", name, version); + } + + /** + * Constructor. + * @param identifier the key vault key identifier. + */ + public KeyIdentifier(String identifier) { + super("keys", identifier); + } +} 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 new file mode 100755 index 000000000000..0d6f8c287997 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java @@ -0,0 +1,1753 @@ +/** + * 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; + +import java.util.List; + +import com.google.common.base.Joiner; +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.PagedList; +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.KeyBundle; +import com.microsoft.azure.keyvault.models.KeyItem; +import com.microsoft.azure.keyvault.models.KeyOperationResult; +import com.microsoft.azure.keyvault.models.KeyVerifyResult; +import com.microsoft.azure.keyvault.models.SecretBundle; +import com.microsoft.azure.keyvault.models.SecretItem; +import com.microsoft.azure.keyvault.requests.CreateCertificateRequest; +import com.microsoft.azure.keyvault.requests.CreateKeyRequest; +import com.microsoft.azure.keyvault.requests.ImportCertificateRequest; +import com.microsoft.azure.keyvault.requests.ImportKeyRequest; +import com.microsoft.azure.keyvault.requests.MergeCertificateRequest; +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.rest.RestClient; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.protocol.SerializerAdapter; + +import okhttp3.OkHttpClient; +import okhttp3.ResponseBody; +import retrofit2.Response; +import retrofit2.Retrofit; +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. + */ +public final class KeyVaultClient { + + private KeyVaultClientImpl innerKeyVaultClient; + + /** The Retrofit service to perform REST calls. */ + private KeyVaultClientService service; + + /** + * Gets the {@link AzureClient} used for long running operations. + * + * @return the azure client; + */ + public AzureClient getAzureClient() { + return innerKeyVaultClient.getAzureClient(); + } + + /** + * Gets Client Api Version. + * + * @return the apiVersion value. + */ + public String apiVersion() { + return innerKeyVaultClient.apiVersion(); + } + + /** + * Gets Gets or sets the preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return innerKeyVaultClient.acceptLanguage(); + } + + /** + * Sets Gets or sets the preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + */ + public void withAcceptLanguage(String acceptLanguage) { + innerKeyVaultClient.withAcceptLanguage(acceptLanguage); + } + + /** + * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return innerKeyVaultClient.longRunningOperationRetryTimeout(); + } + + /** + * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + */ + public void withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + innerKeyVaultClient.withLongRunningOperationRetryTimeout(longRunningOperationRetryTimeout); + } + + /** + * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return innerKeyVaultClient.generateClientRequestId(); + } + + /** + * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + */ + public void withGenerateClientRequestId(boolean generateClientRequestId) { + innerKeyVaultClient.withGenerateClientRequestId(generateClientRequestId); + } + + /** + * @return the {@link RestClient} instance. + */ + public RestClient restClient() { + return innerKeyVaultClient.restClient(); + } + + /** + * @return the Retrofit instance. + */ + public Retrofit retrofit() { + return innerKeyVaultClient.retrofit(); + } + + /** + * @return the HTTP client. + */ + public OkHttpClient httpClient() { + return innerKeyVaultClient.httpClient(); + } + + /** + * @return the adapter to a Jackson {@link com.fasterxml.jackson.databind.ObjectMapper}. + */ + public SerializerAdapter serializerAdapter() { + return innerKeyVaultClient.serializerAdapter(); + } + + /** + * Initializes an instance of KeyVaultClient client. + * + * @param credentials the management credentials for Azure + */ + public KeyVaultClient(ServiceClientCredentials credentials) { + innerKeyVaultClient = new KeyVaultClientImpl(credentials); + initializeService(); + } + + /** + * Initializes an instance of KeyVaultClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public KeyVaultClient(RestClient restClient) { + innerKeyVaultClient = new KeyVaultClientImpl(restClient); + initializeService(); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + public String userAgent() { + return innerKeyVaultClient.userAgent(); + } + + private void initializeService() { + service = innerKeyVaultClient.restClient().retrofit().create(KeyVaultClientService.class); + } + + /** + * The interface defining all the services for KeyVaultClient to be + * used by Retrofit to perform actually REST calls. + */ + interface KeyVaultClientService { + @Headers({ "Content-Type: application/json; charset=utf-8", "Accept: application/pkcs10", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getPendingCertificateSigningRequest" }) + @GET("certificates/{certificate-name}/pending") + 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); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param createKeyRequest the grouped properties for creating a key request + * @return the KeyBundle if successful. + */ + public KeyBundle createKey(CreateKeyRequest createKeyRequest) { + return innerKeyVaultClient.createKey( + createKeyRequest.vaultBaseUrl(), + createKeyRequest.keyName(), + createKeyRequest.keyType(), + createKeyRequest.keySize(), + createKeyRequest.keyOperations(), + createKeyRequest.keyAttributes(), + createKeyRequest.tags()); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param createKeyRequest the grouped properties for creating a key request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createKeyAsync(CreateKeyRequest createKeyRequest, ServiceCallback serviceCallback) { + return innerKeyVaultClient.createKeyAsync( + createKeyRequest.vaultBaseUrl(), + createKeyRequest.keyName(), + createKeyRequest.keyType(), + createKeyRequest.keySize(), + createKeyRequest.keyOperations(), + createKeyRequest.keyAttributes(), + createKeyRequest.tags(), + serviceCallback); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param importKeyRequest the grouped properties for importing a key request + * + * @return the KeyBundle if successful. + */ + public KeyBundle importKey(ImportKeyRequest importKeyRequest) { + return innerKeyVaultClient.importKey( + importKeyRequest.vaultBaseUrl(), + importKeyRequest.keyName(), + importKeyRequest.key(), + importKeyRequest.isHsm(), + importKeyRequest.keyAttributes(), + importKeyRequest.tags()); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param importKeyRequest the grouped properties for importing a key request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture importKeyAsync(ImportKeyRequest importKeyRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.importKeyAsync( + importKeyRequest.vaultBaseUrl(), + importKeyRequest.keyName(), + importKeyRequest.key(), + importKeyRequest.isHsm(), + importKeyRequest.keyAttributes(), + importKeyRequest.tags(), + serviceCallback); + } + + /** + * Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the KeyBundle if successful. + */ + public KeyBundle deleteKey(String vaultBaseUrl, String keyName) { + return innerKeyVaultClient.deleteKey(vaultBaseUrl, keyName); + } + + /** + * Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission. + * + * @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 ServiceFuture} object + */ + public ServiceFuture deleteKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.deleteKeyAsync(vaultBaseUrl, keyName, serviceCallback); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param updateKeyRequest the grouped properties for updating a key request + * + * @return the KeyBundle if successful. + */ + public KeyBundle updateKey(UpdateKeyRequest updateKeyRequest) { + return innerKeyVaultClient.updateKey( + updateKeyRequest.vaultBaseUrl(), + updateKeyRequest.keyName(), + updateKeyRequest.keyVersion(), + updateKeyRequest.keyOperations(), + updateKeyRequest.keyAttributes(), + updateKeyRequest.tags()); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param updateKeyRequest the grouped properties for updating a key request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateKeyAsync(UpdateKeyRequest updateKeyRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.updateKeyAsync( + updateKeyRequest.vaultBaseUrl(), + updateKeyRequest.keyName(), + updateKeyRequest.keyVersion(), + updateKeyRequest.keyOperations(), + updateKeyRequest.keyAttributes(), + updateKeyRequest.tags(), + serviceCallback); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param keyIdentifier The full key identifier + * + * @return the KeyBundle if successful. + */ + public KeyBundle getKey(String keyIdentifier) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.getKey(id.vault, id.name, id.version == null ? "" : id.version); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param keyIdentifier The full key identifier + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getKeyAsync(String keyIdentifier, final ServiceCallback serviceCallback) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.getKeyAsync(id.vault, id.name, id.version == null ? "" : id.version, serviceCallback); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * @return the KeyBundle if successful. + */ + public KeyBundle getKey(String vaultBaseUrl, String keyName) { + return innerKeyVaultClient.getKey(vaultBaseUrl, keyName, ""); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @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 ServiceFuture} object + */ + public ServiceFuture getKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getKeyAsync(vaultBaseUrl, keyName, "", serviceCallback); + } + + /** + *Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @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 KeyBundle if successful. + */ + public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) { + return innerKeyVaultClient.getKey(vaultBaseUrl, keyName, keyVersion); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getKeyAsync(vaultBaseUrl, keyName, keyVersion, serviceCallback); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param keyName The name of the key + * + * @return the PagedList<KeyItem> if successful. + */ + public PagedList listKeyVersions(final String vaultBaseUrl, final String keyName) { + return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @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 ServiceFuture} object + */ + public ServiceFuture> listKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getKeyVersionsAsync(vaultBaseUrl, keyName, serviceCallback); + } + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @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 PagedList<KeyItem> if successful. + */ + public PagedList listKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) { + return innerKeyVaultClient.getKeyVersions(vaultBaseUrl, keyName, maxresults); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getKeyVersionsAsync(vaultBaseUrl, keyName, maxresults, serviceCallback); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * + * @return the PagedList<KeyItem> if successful. + */ + public PagedList listKeys(final String vaultBaseUrl) { + return innerKeyVaultClient.getKeys(vaultBaseUrl); + } + + /** + * List keys in the specified vault. + * + * @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 ServiceFuture} object + */ + public ServiceFuture> 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 in a page. If not specified the service will return up to 25 results. + * + * @return the PagedList<KeyItem> if successful. + */ + public PagedList listKeys(final String vaultBaseUrl, final Integer maxresults) { + return innerKeyVaultClient.getKeys(vaultBaseUrl, maxresults); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listKeysAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getKeysAsync(vaultBaseUrl, maxresults, 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 BackupKeyResult if successful. + */ + public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) { + return innerKeyVaultClient.backupKey(vaultBaseUrl, keyName); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture backupKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.backupKeyAsync(vaultBaseUrl, keyName, 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 KeyBundle if successful. + */ + public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) { + return innerKeyVaultClient.restoreKey(vaultBaseUrl, keyBundleBackup); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.restoreKeyAsync(vaultBaseUrl, keyBundleBackup, serviceCallback); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the content to be encrypted + * + * @return the KeyOperationResult if successful. + */ + public KeyOperationResult encrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.encrypt(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the content to be encrypted + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture 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); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the content to be decrypted + * + * @return the KeyOperationResult if successful. + */ + public KeyOperationResult decrypt(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.decrypt(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the content to be decrypted + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture 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); + } + + /** + * Creates a signature from a digest using the specified key. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the content to be signed + * + * @return the KeyOperationResult if successful. + */ + public KeyOperationResult sign(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.sign(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); + } + + /** + * Creates a signature from a digest using the specified key. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the content to be signed + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture 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); + } + + /** + * Verifies a signature using the specified key. + * + * @param keyIdentifier The full key identifier + * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. + * @param digest The digest used for signing + * @param signature The signature to be verified + * + * @return the KeyVerifyResult if successful. + */ + public KeyVerifyResult verify(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.verify(id.vault, id.name, id.version == null ? "" : id.version, algorithm, digest, signature); + } + + /** + * Verifies a signature using the specified key. + * + * @param keyIdentifier The full key identifier + * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. + * @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 ServiceFuture} object + */ + public ServiceFuture 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); + } + + /** + * Wraps a symmetric key using the specified key. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the key to be wrapped + * + * @return the KeyOperationResult if successful. + */ + public KeyOperationResult wrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.wrapKey(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); + } + + /** + * Wraps a symmetric key using the specified key. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the key to be wrapped + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture 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); + } + + /** + * Unwraps a symmetric key using the specified key in the vault that has initially been used for wrapping the key. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the key to be unwrapped + * + * @return the KeyOperationResult if successful. + */ + public KeyOperationResult unwrapKey(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + return innerKeyVaultClient.unwrapKey(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value); + } + + /** + * Unwraps a symmetric key using the specified key in the vault that has initially been used for wrapping the key. + * + * @param keyIdentifier The full key identifier + * @param algorithm algorithm identifier + * @param value the key to be unwrapped + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture 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); + } + + /** + * Sets a secret in the specified vault. + * + * @param setSecretRequest the grouped properties for setting a secret request + * + * @return the SecretBundle if successful. + */ + public SecretBundle setSecret(SetSecretRequest setSecretRequest) { + return innerKeyVaultClient.setSecret( + setSecretRequest.vaultBaseUrl(), + setSecretRequest.secretName(), + setSecretRequest.value(), + setSecretRequest.tags(), + setSecretRequest.contentType(), + setSecretRequest.secretAttributes()); + } + + /** + * Sets a secret in the specified vault. + * + * @param setSecretRequest the grouped properties for setting a secret request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setSecretAsync(SetSecretRequest setSecretRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.setSecretAsync( + setSecretRequest.vaultBaseUrl(), + setSecretRequest.secretName(), + setSecretRequest.value(), + setSecretRequest.tags(), + setSecretRequest.contentType(), + setSecretRequest.secretAttributes(), + 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 SecretBundle if successful. + */ + public SecretBundle deleteSecret(String vaultBaseUrl, String secretName) { + return innerKeyVaultClient.deleteSecret(vaultBaseUrl, secretName); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteSecretAsync(String vaultBaseUrl, String secretName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.deleteSecretAsync(vaultBaseUrl, secretName, serviceCallback); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param updateSecretRequest the grouped properties for updating a secret request + * + * @return the SecretBundle if successful. + */ + public SecretBundle updateSecret(UpdateSecretRequest updateSecretRequest) { + return innerKeyVaultClient.updateSecret( + updateSecretRequest.vaultBaseUrl(), + updateSecretRequest.secretName(), + updateSecretRequest.secretVersion(), + updateSecretRequest.contentType(), + updateSecretRequest.secretAttributes(), + updateSecretRequest.tags()); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param updateSecretRequest the grouped properties for updating a secret request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateSecretAsync(UpdateSecretRequest updateSecretRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.updateSecretAsync( + updateSecretRequest.vaultBaseUrl(), + updateSecretRequest.secretName(), + updateSecretRequest.secretVersion(), + updateSecretRequest.contentType(), + updateSecretRequest.secretAttributes(), + updateSecretRequest.tags(), + serviceCallback); + } + + /** + * Get a specified secret from a given key vault. + * + * @param secretIdentifier The URL for the secret. + * + * @return the SecretBundle if successful. + */ + public SecretBundle getSecret(String secretIdentifier) { + SecretIdentifier id = new SecretIdentifier(secretIdentifier); + return innerKeyVaultClient.getSecret(id.vault, id.name, id.version == null ? "" : id.version); + } + + /** + * Get a specified secret from a given key vault. + * + * @param secretIdentifier The URL for the secret. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getSecretAsync(String secretIdentifier, final ServiceCallback serviceCallback) { + SecretIdentifier id = new SecretIdentifier(secretIdentifier); + return innerKeyVaultClient.getSecretAsync(id.vault, id.name, id.version == null ? "" : id.version, serviceCallback); + } + + /** + * Get a specified secret from a given key 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 SecretBundle if successful. + */ + public SecretBundle getSecret(String vaultBaseUrl, String secretName) { + return innerKeyVaultClient.getSecret(vaultBaseUrl, secretName, ""); + } + + /** + * Get a specified secret from a given key 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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getSecretAsync(String vaultBaseUrl, String secretName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getSecretAsync(vaultBaseUrl, secretName, "", serviceCallback); + } + + /** + * Get a specified secret from a given key 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 secretVersion The version of the secret + * + * @return the SecretBundle if successful. + */ + public SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) { + return innerKeyVaultClient.getSecret(vaultBaseUrl, secretName, secretVersion == null ? "" : secretVersion); + } + + /** + * Get a specified secret from a given key 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 secretVersion The version of the secret + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getSecretAsync(vaultBaseUrl, secretName, secretVersion == null ? "" : secretVersion, serviceCallback); + } + + /** + * List secrets in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * + * @return the PagedList<SecretItem> if successful. + */ + public PagedList listSecrets(final String vaultBaseUrl) { + return innerKeyVaultClient.getSecrets(vaultBaseUrl); + } + + /** + * List secrets in the specified vault. + * + * @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 ServiceFuture} object + */ + public ServiceFuture> 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 results to return in a page. If not specified the service will return up to 25 results. + * + * @return the PagedList<SecretItem> if successful. + */ + public PagedList listSecrets(final String vaultBaseUrl, final Integer maxresults) { + return innerKeyVaultClient.getSecrets(vaultBaseUrl, maxresults); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listSecretsAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getSecretsAsync(vaultBaseUrl, maxresults, 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 PagedList<SecretItem> if successful. + */ + public PagedList listSecretVersions(final String vaultBaseUrl, final String secretName) { + return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName); + } + + /** + * 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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getSecretVersionsAsync(vaultBaseUrl, secretName, 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 PagedList<SecretItem> if successful. + */ + public PagedList listSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) { + return innerKeyVaultClient.getSecretVersions(vaultBaseUrl, secretName, maxresults); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getSecretVersionsAsync(vaultBaseUrl, secretName, maxresults, serviceCallback); + } + + /** + * List certificates in the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * + * @return the PagedList<CertificateItem> if successful. + */ + public PagedList listCertificates(final String vaultBaseUrl) { + return innerKeyVaultClient.getCertificates(vaultBaseUrl); + } + + /** + * List certificates in the specified vault. + * + * @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 ServiceFuture} object + */ + public ServiceFuture> 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 in a page. If not specified the service will return up to 25 results. + * + * @return the PagedList<CertificateItem> if successful. + */ + public PagedList listCertificates(final String vaultBaseUrl, final Integer maxresults) { + return innerKeyVaultClient.getCertificates(vaultBaseUrl, maxresults); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listCertificatesAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getCertificatesAsync(vaultBaseUrl, maxresults, 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 CertificateBundle if successful. + */ + public CertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) { + return innerKeyVaultClient.deleteCertificate(vaultBaseUrl, certificateName); + } + + /** + * 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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.deleteCertificateAsync(vaultBaseUrl, certificateName, 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 Contacts if successful. + */ + public Contacts setCertificateContacts(String vaultBaseUrl, Contacts contacts) { + return innerKeyVaultClient.setCertificateContacts(vaultBaseUrl, contacts); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.setCertificateContactsAsync(vaultBaseUrl, contacts, serviceCallback); + } + + /** + * Gets the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * + * @return the Contacts if successful. + */ + public Contacts getCertificateContacts(String vaultBaseUrl) { + return innerKeyVaultClient.getCertificateContacts(vaultBaseUrl); + } + + /** + * Gets the certificate contacts for the specified vault. + * + * @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 ServiceFuture} object + */ + public ServiceFuture getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getCertificateContactsAsync(vaultBaseUrl, serviceCallback); + } + + /** + * Deletes the certificate contacts for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * + * @return the Contacts if successful. + */ + public Contacts deleteCertificateContacts(String vaultBaseUrl) { + return innerKeyVaultClient.deleteCertificateContacts(vaultBaseUrl); + } + + /** + * Deletes the certificate contacts for the specified vault. + * + * @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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.deleteCertificateContactsAsync(vaultBaseUrl, serviceCallback); + } + + /** + * List certificate issuers for the specified vault. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * + * @return the PagedList<CertificateIssuerItem> if successful. + */ + public PagedList listCertificateIssuers(final String vaultBaseUrl) { + return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl); + } + + /** + * List certificate issuers for the specified vault. + * + * @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 ServiceFuture} object + */ + public ServiceFuture> 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 in a page. If not specified the service will return up to 25 results. + * + * @return the PagedList<CertificateIssuerItem> if successful. + */ + public PagedList listCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) { + return innerKeyVaultClient.getCertificateIssuers(vaultBaseUrl, maxresults); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getCertificateIssuersAsync(vaultBaseUrl, maxresults, serviceCallback); + } + + /** + * Sets the certificate contacts for the specified vault. + * + * @param setCertificateIssuerRequest the grouped properties for setting a certificate issuer request + * + * @return the IssuerBundle if successful. + */ + public IssuerBundle setCertificateIssuer(SetCertificateIssuerRequest setCertificateIssuerRequest) { + return innerKeyVaultClient.setCertificateIssuer( + setCertificateIssuerRequest.vaultBaseUrl(), + setCertificateIssuerRequest.issuerName(), + setCertificateIssuerRequest.provider(), + setCertificateIssuerRequest.credentials(), + setCertificateIssuerRequest.organizationDetails(), + setCertificateIssuerRequest.attributes()); + } + + /** + * Sets the certificate contacts for the specified vault. + * + * @param setCertificateIssuerRequest the grouped properties for setting a certificate issuer request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setCertificateIssuerAsync(SetCertificateIssuerRequest setCertificateIssuerRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.setCertificateIssuerAsync( + setCertificateIssuerRequest.vaultBaseUrl(), + setCertificateIssuerRequest.issuerName(), + setCertificateIssuerRequest.provider(), + setCertificateIssuerRequest.credentials(), + setCertificateIssuerRequest.organizationDetails(), + setCertificateIssuerRequest.attributes(), + serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param updateCertificateIssuerRequest the grouped properties for updating a certificate issuer request + * + * @return the IssuerBundle if successful. + */ + public IssuerBundle updateCertificateIssuer(UpdateCertificateIssuerRequest updateCertificateIssuerRequest) { + return innerKeyVaultClient.updateCertificateIssuer( + updateCertificateIssuerRequest.vaultBaseUrl(), + updateCertificateIssuerRequest.issuerName(), + updateCertificateIssuerRequest.provider(), + updateCertificateIssuerRequest.credentials(), + updateCertificateIssuerRequest.organizationDetails(), + updateCertificateIssuerRequest.attributes()); + } + + /** + * Updates the specified certificate issuer. + * + * @param updateCertificateIssuerRequest the grouped properties for updating a certificate issuer request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificateIssuerAsync(UpdateCertificateIssuerRequest updateCertificateIssuerRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.updateCertificateIssuerAsync( + updateCertificateIssuerRequest.vaultBaseUrl(), + updateCertificateIssuerRequest.issuerName(), + updateCertificateIssuerRequest.provider(), + updateCertificateIssuerRequest.credentials(), + updateCertificateIssuerRequest.organizationDetails(), + updateCertificateIssuerRequest.attributes(), + 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 IssuerBundle if successful. + */ + public IssuerBundle getCertificateIssuer(String vaultBaseUrl, String issuerName) { + return innerKeyVaultClient.getCertificateIssuer(vaultBaseUrl, issuerName); + } + + /** + * Gets the specified certificate issuer. + * + * @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 ServiceFuture} object + */ + public ServiceFuture getCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getCertificateIssuerAsync(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 IssuerBundle if successful. + */ + public IssuerBundle deleteCertificateIssuer(String vaultBaseUrl, String issuerName) { + return innerKeyVaultClient.deleteCertificateIssuer(vaultBaseUrl, issuerName); + } + + /** + * Deletes the specified certificate issuer. + * + * @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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.deleteCertificateIssuerAsync(vaultBaseUrl, issuerName, serviceCallback); + } + + /** + * Creates a new certificate version. If this is the first version, the certificate resource is created. + * + * @param createCertificateRequest the grouped properties for creating a certificate request + * + * @return the CertificateOperation if successful. + */ + public CertificateOperation createCertificate(CreateCertificateRequest createCertificateRequest) { + return innerKeyVaultClient.createCertificate( + createCertificateRequest.vaultBaseUrl(), + createCertificateRequest.certificateName(), + createCertificateRequest.certificatePolicy(), + createCertificateRequest.certificateAttributes(), + createCertificateRequest.tags()); + } + + /** + * Creates a new certificate version. If this is the first version, the certificate resource is created. + * + * @param createCertificateRequest the grouped properties for creating a certificate request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createCertificateAsync(CreateCertificateRequest createCertificateRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.createCertificateAsync( + createCertificateRequest.vaultBaseUrl(), + createCertificateRequest.certificateName(), + createCertificateRequest.certificatePolicy(), + createCertificateRequest.certificateAttributes(), + createCertificateRequest.tags(), + serviceCallback); + } + + /** + * Imports a certificate into the specified vault. + * + * @param importCertificateRequest the grouped properties for importing a certificate request + * + * @return the CertificateBundle if successful. + */ + public CertificateBundle importCertificate(ImportCertificateRequest importCertificateRequest) { + return innerKeyVaultClient.importCertificate( + importCertificateRequest.vaultBaseUrl(), + importCertificateRequest.certificateName(), + importCertificateRequest.base64EncodedCertificate(), + importCertificateRequest.password(), + importCertificateRequest.certificatePolicy(), + importCertificateRequest.certificateAttributes(), + importCertificateRequest.tags()); + } + + /** + * Imports a certificate into the specified vault. + * + * @param importCertificateRequest the grouped properties for importing a certificate request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture importCertificateAsync(ImportCertificateRequest importCertificateRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.importCertificateAsync( + importCertificateRequest.vaultBaseUrl(), + importCertificateRequest.certificateName(), + importCertificateRequest.base64EncodedCertificate(), + importCertificateRequest.password(), + importCertificateRequest.certificatePolicy(), + importCertificateRequest.certificateAttributes(), + importCertificateRequest.tags(), + 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 PagedList<CertificateItem> if successful. + */ + public PagedList listCertificateVersions(final String vaultBaseUrl, final String certificateName) { + return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName); + } + + /** + * 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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getCertificateVersionsAsync(vaultBaseUrl, certificateName, 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 PagedList<CertificateItem> if successful. + */ + public PagedList listCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { + return innerKeyVaultClient.getCertificateVersions(vaultBaseUrl, certificateName, maxresults); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return innerKeyVaultClient.getCertificateVersionsAsync(vaultBaseUrl, certificateName, maxresults, 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 CertificatePolicy if successful. + */ + public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) { + return innerKeyVaultClient.getCertificatePolicy(vaultBaseUrl, certificateName); + } + + /** + * 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getCertificatePolicyAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getCertificatePolicyAsync(vaultBaseUrl, certificateName, serviceCallback); + } + + /** + * Updates the policy for a certificate. Set appropriate members in the certificatePolicy that must be updated. Leave others as null. + * + * @param updateCertificatePolicyRequest the grouped properties for updating a certificate policy request + * + * @return the CertificatePolicy if successful. + */ + public CertificatePolicy updateCertificatePolicy(UpdateCertificatePolicyRequest updateCertificatePolicyRequest) { + return innerKeyVaultClient.updateCertificatePolicy( + updateCertificatePolicyRequest.vaultBaseUrl(), + updateCertificatePolicyRequest.certificateName(), + updateCertificatePolicyRequest.certificatePolicy()); + } + + /** + * Updates the policy for a certificate. Set appropriate members in the certificatePolicy that must be updated. Leave others as null. + * + * @param updateCertificatePolicyRequest the grouped properties for updating a certificate policy request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificatePolicyAsync(UpdateCertificatePolicyRequest updateCertificatePolicyRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.updateCertificatePolicyAsync( + updateCertificatePolicyRequest.vaultBaseUrl(), + updateCertificatePolicyRequest.certificateName(), + updateCertificatePolicyRequest.certificatePolicy(), + serviceCallback); + } + + /** + * Updates the attributes associated with the specified certificate. + * + * @param updateCertificateRequest the grouped properties for updating a certificate request + * + * @return the CertificateBundle if successful. + */ + public CertificateBundle updateCertificate(UpdateCertificateRequest updateCertificateRequest) { + return innerKeyVaultClient.updateCertificate( + updateCertificateRequest.vaultBaseUrl(), + updateCertificateRequest.certificateName(), + updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificatePolicy(), + updateCertificateRequest.certificateAttributes(), + updateCertificateRequest.tags()); + } + + /** + * Updates the attributes associated with the specified certificate. + * + * @param updateCertificateRequest the grouped properties for updating a certificate request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificateAsync(UpdateCertificateRequest updateCertificateRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.updateCertificateAsync( + updateCertificateRequest.vaultBaseUrl(), + updateCertificateRequest.certificateName(), + updateCertificateRequest.certificateVersion(), + updateCertificateRequest.certificatePolicy(), + updateCertificateRequest.certificateAttributes(), + updateCertificateRequest.tags(), + serviceCallback); + } + + /** + * Gets information about a specified certificate. + * + * @param certificateIdentifier The certificate identifier + * + * @return the CertificateBundle if successful. + */ + public CertificateBundle getCertificate(String certificateIdentifier) { + CertificateIdentifier id = new CertificateIdentifier(certificateIdentifier); + return innerKeyVaultClient.getCertificate(id.vault, id.name, id.version == null ? "" : id.version); + } + + /** + * Gets information about a specified certificate. + * + * @param certificateIdentifier The certificate identifier + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getCertificateAsync(String certificateIdentifier, final ServiceCallback serviceCallback) { + CertificateIdentifier id = new CertificateIdentifier(certificateIdentifier); + return innerKeyVaultClient.getCertificateAsync(id.vault, id.name, id.version == null ? "" : id.version, serviceCallback); + } + + /** + * Gets information about a 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 + * + * @return the CertificateBundle if successful. + */ + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName) { + return innerKeyVaultClient.getCertificate(vaultBaseUrl, certificateName, ""); + } + + /** + * Gets information about a 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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getCertificateAsync(vaultBaseUrl, certificateName, "", serviceCallback); + } + + /** + * Gets information about a 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 CertificateBundle if successful. + */ + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) { + return innerKeyVaultClient.getCertificate(vaultBaseUrl, certificateName, certificateVersion); + } + + /** + * Gets information about a 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 serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getCertificateAsync(vaultBaseUrl, certificateName, certificateVersion, serviceCallback); + } + + /** + * Updates a certificate operation. + * + * @param updateCertificateOperationRequest the grouped properties for updating a certificate operation request + * + * @return the CertificateOperation if successful. + */ + public CertificateOperation updateCertificateOperation(UpdateCertificateOperationRequest updateCertificateOperationRequest) { + return innerKeyVaultClient.updateCertificateOperation( + updateCertificateOperationRequest.vaultBaseUrl(), + updateCertificateOperationRequest.certificateName(), + updateCertificateOperationRequest.cancellationRequested()); + } + + /** + * Updates a certificate operation. + * + * @param updateCertificateOperationRequest the grouped properties for updating a certificate operation request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificateOperationAsync(UpdateCertificateOperationRequest updateCertificateOperationRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.updateCertificateOperationAsync( + updateCertificateOperationRequest.vaultBaseUrl(), + updateCertificateOperationRequest.certificateName(), + updateCertificateOperationRequest.cancellationRequested(), + serviceCallback); + } + + /** + * Gets the operation associated with a specified certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * + * @return the CertificateOperation if successful. + */ + public CertificateOperation getCertificateOperation(String vaultBaseUrl, String certificateName) { + return innerKeyVaultClient.getCertificateOperation(vaultBaseUrl, certificateName); + } + + /** + * Gets the operation associated with a specified certificate. + * + * @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 ServiceFuture} object + */ + public ServiceFuture getCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.getCertificateOperationAsync(vaultBaseUrl, certificateName, serviceCallback); + } + + /** + * Deletes the operation for a specified certificate. + * + * @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName The name of the certificate + * + * @return the CertificateOperation if successful. + */ + public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) { + return innerKeyVaultClient.deleteCertificateOperation(vaultBaseUrl, certificateName); + } + + /** + * Deletes the operation for a specified certificate. + * + * @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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.deleteCertificateOperationAsync(vaultBaseUrl, certificateName, serviceCallback); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param mergeCertificateRequest the grouped properties for merging a certificate request + * + * @return the CertificateBundle if successful. + */ + public CertificateBundle mergeCertificate(MergeCertificateRequest mergeCertificateRequest) { + return innerKeyVaultClient.mergeCertificate( + mergeCertificateRequest.vaultBaseUrl(), + mergeCertificateRequest.certificateName(), + mergeCertificateRequest.x509Certificates(), + mergeCertificateRequest.certificateAttributes(), + mergeCertificateRequest.tags()); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param mergeCertificateRequest the grouped properties for merging a certificate request + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture mergeCertificateAsync(MergeCertificateRequest mergeCertificateRequest, final ServiceCallback serviceCallback) { + return innerKeyVaultClient.mergeCertificateAsync( + mergeCertificateRequest.vaultBaseUrl(), + mergeCertificateRequest.certificateName(), + mergeCertificateRequest.x509Certificates(), + mergeCertificateRequest.certificateAttributes(), + mergeCertificateRequest.tags(), + 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 String if successful. + */ + public String getPendingCertificateSigningRequest(String vaultBaseUrl, String certificateName) { + return getPendingCertificateSigningRequestWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); + } + + /** + * 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 + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getPendingCertificateSigningRequestAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(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."); + } + 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); + 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); + } + } + }); + } +} 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 new file mode 100755 index 000000000000..e2d082710b89 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java @@ -0,0 +1,6823 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault; + +import com.google.common.base.Joiner; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.AzureServiceClient; +import com.microsoft.azure.keyvault.models.BackupKeyResult; +import com.microsoft.azure.keyvault.models.CertificateAttributes; +import com.microsoft.azure.keyvault.models.CertificateBundle; +import com.microsoft.azure.keyvault.models.CertificateCreateParameters; +import com.microsoft.azure.keyvault.models.CertificateImportParameters; +import com.microsoft.azure.keyvault.models.CertificateIssuerItem; +import com.microsoft.azure.keyvault.models.CertificateIssuerSetParameters; +import com.microsoft.azure.keyvault.models.CertificateIssuerUpdateParameters; +import com.microsoft.azure.keyvault.models.CertificateItem; +import com.microsoft.azure.keyvault.models.CertificateMergeParameters; +import com.microsoft.azure.keyvault.models.CertificateOperation; +import com.microsoft.azure.keyvault.models.CertificateOperationUpdateParameter; +import com.microsoft.azure.keyvault.models.CertificatePolicy; +import com.microsoft.azure.keyvault.models.CertificateUpdateParameters; +import com.microsoft.azure.keyvault.models.Contacts; +import com.microsoft.azure.keyvault.models.IssuerAttributes; +import com.microsoft.azure.keyvault.models.IssuerBundle; +import com.microsoft.azure.keyvault.models.IssuerCredentials; +import com.microsoft.azure.keyvault.models.KeyAttributes; +import com.microsoft.azure.keyvault.models.KeyBundle; +import com.microsoft.azure.keyvault.models.KeyCreateParameters; +import com.microsoft.azure.keyvault.models.KeyImportParameters; +import com.microsoft.azure.keyvault.models.KeyItem; +import com.microsoft.azure.keyvault.models.KeyOperationResult; +import com.microsoft.azure.keyvault.models.KeyOperationsParameters; +import com.microsoft.azure.keyvault.models.KeyRestoreParameters; +import com.microsoft.azure.keyvault.models.KeySignParameters; +import com.microsoft.azure.keyvault.models.KeyUpdateParameters; +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.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestClient; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +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. + */ +final class KeyVaultClientImpl extends AzureServiceClient { + /** The Retrofit service to perform REST calls. */ + private KeyVaultClientService service; + /** the {@link AzureClient} used for long running operations. */ + private AzureClient azureClient; + + /** + * Gets the {@link AzureClient} used for long running operations. + * @return the azure client; + */ + public AzureClient getAzureClient() { + return this.azureClient; + } + + /** Client API version. */ + private String apiVersion; + + /** + * Gets Client API version. + * + * @return the apiVersion value. + */ + public String apiVersion() { + return this.apiVersion; + } + + /** Gets or sets the preferred language for the response. */ + private String acceptLanguage; + + /** + * Gets Gets or sets the preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return this.acceptLanguage; + } + + /** + * Sets Gets or sets the preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + * @return the service client itself + */ + public KeyVaultClientImpl withAcceptLanguage(String acceptLanguage) { + this.acceptLanguage = acceptLanguage; + return this; + } + + /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ + private int longRunningOperationRetryTimeout; + + /** + * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return this.longRunningOperationRetryTimeout; + } + + /** + * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + * @return the service client itself + */ + public KeyVaultClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; + return this; + } + + /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + private boolean generateClientRequestId; + + /** + * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return this.generateClientRequestId; + } + + /** + * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + * @return the service client itself + */ + public KeyVaultClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { + this.generateClientRequestId = generateClientRequestId; + return this; + } + + /** + * Initializes an instance of KeyVaultClient client. + * + * @param credentials the management credentials for Azure + */ + public KeyVaultClientImpl(ServiceClientCredentials credentials) { + this("https://{vaultBaseUrl}", credentials); + } + + /** + * Initializes an instance of KeyVaultClient client. + * + * @param baseUrl the base URL of the host + * @param credentials the management credentials for Azure + */ + private KeyVaultClientImpl(String baseUrl, ServiceClientCredentials credentials) { + super(baseUrl, credentials); + initialize(); + } + + /** + * Initializes an instance of KeyVaultClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public KeyVaultClientImpl(RestClient restClient) { + super(restClient); + initialize(); + } + + protected void initialize() { + this.apiVersion = "2016-10-01"; + this.acceptLanguage = "en-US"; + this.longRunningOperationRetryTimeout = 30; + this.generateClientRequestId = true; + this.azureClient = new AzureClient(this); + initializeService(); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + @Override + public String userAgent() { + return String.format("Azure-SDK-For-Java/%s (%s)", + getClass().getPackage().getImplementationVersion(), + "KeyVaultClient, 2016-10-01"); + } + + private void initializeService() { + service = restClient().retrofit().create(KeyVaultClientService.class); + } + + /** + * The interface defining all the services for KeyVaultClient to be + * used by Retrofit to perform actually REST calls. + */ + interface KeyVaultClientService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient createKey" }) + @POST("keys/{key-name}/create") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient importKey" }) + @PUT("keys/{key-name}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient deleteKey" }) + @HTTP(path = "keys/{key-name}", method = "DELETE", hasBody = true) + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient updateKey" }) + @PATCH("keys/{key-name}/{key-version}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getKey" }) + @GET("keys/{key-name}/{key-version}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getKeyVersions" }) + @GET("keys/{key-name}/versions") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getKeys" }) + @GET("keys") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient backupKey" }) + @POST("keys/{key-name}/backup") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient restoreKey" }) + @POST("keys/restore") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient encrypt" }) + @POST("keys/{key-name}/{key-version}/encrypt") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient decrypt" }) + @POST("keys/{key-name}/{key-version}/decrypt") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient sign" }) + @POST("keys/{key-name}/{key-version}/sign") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient verify" }) + @POST("keys/{key-name}/{key-version}/verify") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient wrapKey" }) + @POST("keys/{key-name}/{key-version}/wrapkey") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient unwrapKey" }) + @POST("keys/{key-name}/{key-version}/unwrapkey") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient setSecret" }) + @PUT("secrets/{secret-name}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient deleteSecret" }) + @HTTP(path = "secrets/{secret-name}", method = "DELETE", hasBody = true) + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient updateSecret" }) + @PATCH("secrets/{secret-name}/{secret-version}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getSecret" }) + @GET("secrets/{secret-name}/{secret-version}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getSecrets" }) + @GET("secrets") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getSecretVersions" }) + @GET("secrets/{secret-name}/versions") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificates" }) + @GET("certificates") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient deleteCertificate" }) + @HTTP(path = "certificates/{certificate-name}", method = "DELETE", hasBody = true) + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient setCertificateContacts" }) + @PUT("certificates/contacts") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateContacts" }) + @GET("certificates/contacts") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient deleteCertificateContacts" }) + @HTTP(path = "certificates/contacts", method = "DELETE", hasBody = true) + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateIssuers" }) + @GET("certificates/issuers") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient setCertificateIssuer" }) + @PUT("certificates/issuers/{issuer-name}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient updateCertificateIssuer" }) + @PATCH("certificates/issuers/{issuer-name}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateIssuer" }) + @GET("certificates/issuers/{issuer-name}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient deleteCertificateIssuer" }) + @HTTP(path = "certificates/issuers/{issuer-name}", method = "DELETE", hasBody = true) + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient createCertificate" }) + @POST("certificates/{certificate-name}/create") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient importCertificate" }) + @POST("certificates/{certificate-name}/import") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateVersions" }) + @GET("certificates/{certificate-name}/versions") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificatePolicy" }) + @GET("certificates/{certificate-name}/policy") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient updateCertificatePolicy" }) + @PATCH("certificates/{certificate-name}/policy") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient updateCertificate" }) + @PATCH("certificates/{certificate-name}/{certificate-version}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificate" }) + @GET("certificates/{certificate-name}/{certificate-version}") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient updateCertificateOperation" }) + @PATCH("certificates/{certificate-name}/pending") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateOperation" }) + @GET("certificates/{certificate-name}/pending") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient deleteCertificateOperation" }) + @HTTP(path = "certificates/{certificate-name}/pending", method = "DELETE", hasBody = true) + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient mergeCertificate" }) + @POST("certificates/{certificate-name}/pending/merge") + 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", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getKeyVersionsNext" }) + @GET + Observable> getKeyVersionsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getKeysNext" }) + @GET + Observable> getKeysNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getSecretsNext" }) + @GET + Observable> getSecretsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getSecretVersionsNext" }) + @GET + Observable> getSecretVersionsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificatesNext" }) + @GET + Observable> getCertificatesNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateIssuersNext" }) + @GET + Observable> getCertificateIssuersNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.keyvault.KeyVaultClient getCertificateVersionsNext" }) + @GET + Observable> getCertificateVersionsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @return the KeyBundle object if successful. + */ + public KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty).toBlocking().single().body(); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty), serviceCallback); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @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.body(); + } + }); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @return the observable to the KeyBundle object + */ + public Observable> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + 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); + 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); + } + } + }); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param keySize The key size in bytes. For example, 1024 or 2048. + * @param keyOps the List<JsonWebKeyOperation> value + * @param keyAttributes the KeyAttributes value + * @param tags Application specific metadata in the form of key-value pairs. + * @return the KeyBundle object if successful. + */ + public KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) { + return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags).toBlocking().single().body(); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param keySize The key size in bytes. For example, 1024 or 2048. + * @param keyOps the List<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 ServiceFuture} object + */ + public ServiceFuture createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags), serviceCallback); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param keySize The key size in bytes. For example, 1024 or 2048. + * @param keyOps the List<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.body(); + } + }); + } + + /** + * Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: Requires the keys/create permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name for the new key. The system will generate the version name for the new key. + * @param kty The type of key to create. For valid key types, see JsonWebKeyType. Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct' + * @param keySize The key size in bytes. For example, 1024 or 2048. + * @param keyOps the List<JsonWebKeyOperation> value + * @param keyAttributes the KeyAttributes value + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the KeyBundle object + */ + public Observable> createKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List keyOps, KeyAttributes keyAttributes, Map tags) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (keyName == null) { + throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (kty == null) { + throw new IllegalArgumentException("Parameter kty is required and cannot be null."); + } + Validator.validate(keyOps); + Validator.validate(keyAttributes); + Validator.validate(tags); + KeyCreateParameters parameters = new KeyCreateParameters(); + parameters.withKty(kty); + parameters.withKeySize(keySize); + parameters.withKeyOps(keyOps); + parameters.withKeyAttributes(keyAttributes); + parameters.withTags(tags); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + return service.createKey(keyName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse createKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported key. + * @param key The Json web key + * @return the KeyBundle object if successful. + */ + public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key) { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key).toBlocking().single().body(); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported key. + * @param key The Json web key + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key), serviceCallback); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported 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.body(); + } + }); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported 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."); + } + 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); + 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); + } + } + }); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported 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 KeyBundle object if successful. + */ + public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags) { + return importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags).toBlocking().single().body(); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags), serviceCallback); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported 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.body(); + } + }); + } + + /** + * Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. Authorization: requires the keys/import permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName Name for the imported 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse importKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to delete. + * @return the KeyBundle object if successful. + */ + public KeyBundle deleteKey(String vaultBaseUrl, String keyName) { + return deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().body(); + } + + /** + * Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to delete. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName), serviceCallback); + } + + /** + * Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to delete. + * @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.body(); + } + }); + } + + /** + * Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to delete. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse deleteKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @return the KeyBundle object if successful. + */ + public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single().body(); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @return the observable to the KeyBundle object + */ + public Observable updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @return the observable to the KeyBundle object + */ + public Observable> 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 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); + 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); + } + } + }); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @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 KeyBundle object if successful. + */ + public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).toBlocking().single().body(); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags), serviceCallback); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. + * @param keyAttributes the KeyAttributes value + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the KeyBundle object + */ + public Observable updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, KeyAttributes keyAttributes, Map tags) { + return updateKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. The cryptographic material of a key itself cannot be changed. In order to perform this operation, the key must already exist in the Key Vault. Authorization: requires the keys/update permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of key to update. + * @param keyVersion The version of the key to update. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse updateKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to get. + * @param keyVersion Adding the version parameter retrieves a specific version of a key. + * @return the KeyBundle object if successful. + */ + public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) { + return getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion).toBlocking().single().body(); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to get. + * @param keyVersion Adding the version parameter retrieves a specific version of a key. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to get. + * @param keyVersion Adding the version parameter retrieves a specific version of a 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.body(); + } + }); + } + + /** + * Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. Authorization: Requires the keys/get permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key to get. + * @param keyVersion Adding the version parameter retrieves a specific version of a 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse getKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key. + * @return the PagedList<KeyItem> object if successful. + */ + public PagedList getKeyVersions(final String vaultBaseUrl, final String keyName) { + ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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 PagedList<KeyItem> object if successful. + */ + public PagedList getKeyVersions(final String vaultBaseUrl, final String keyName, final Integer maxresults) { + ServiceResponse> response = getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + ServiceResponse> * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getKeyVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @return the PagedList<KeyItem> object if successful. + */ + public PagedList getKeys(final String vaultBaseUrl) { + ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getKeysAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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, for example 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.body(); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + 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, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, for example 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 PagedList<KeyItem> object if successful. + */ + public PagedList getKeys(final String vaultBaseUrl, final Integer maxresults) { + ServiceResponse> response = getKeysSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getKeysAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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, for example 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.body(); + } + }); + } + + /** + * List keys in the specified vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + 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, for example 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."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getKeysDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Requests that a backup of the specified key be downloaded to the client. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key. + * @return the BackupKeyResult object if successful. + */ + public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) { + return backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().body(); + } + + /** + * Requests that a backup of the specified key be downloaded to the client. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture backupKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName), serviceCallback); + } + + /** + * Requests that a backup of the specified key be downloaded to the client. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Requests that a backup of the specified key be downloaded to the client. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse backupKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Restores a backed up key to a vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyBundleBackup The backup blob associated with a key bundle. + * @return the KeyBundle object if successful. + */ + public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) { + return restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup).toBlocking().single().body(); + } + + /** + * Restores a backed up key to a vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyBundleBackup The backup blob associated with a key bundle. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup), serviceCallback); + } + + /** + * Restores a backed up key to a vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyBundleBackup The backup blob associated with a key bundle. + * @return the observable to the KeyBundle object + */ + public Observable restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup) { + return restoreKeyWithServiceResponseAsync(vaultBaseUrl, keyBundleBackup).map(new Func1, KeyBundle>() { + @Override + public KeyBundle call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Restores a backed up key to a vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyBundleBackup The backup blob associated with a key bundle. + * @return the observable to the KeyBundle object + */ + public Observable> restoreKeyWithServiceResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (keyBundleBackup == null) { + throw new IllegalArgumentException("Parameter keyBundleBackup is required and cannot be null."); + } + KeyRestoreParameters parameters = new KeyRestoreParameters(); + parameters.withKeyBundleBackup(keyBundleBackup); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + return service.restoreKey(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = restoreKeyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse restoreKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. + * + * @param vaultBaseUrl The vault name, for example 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 KeyOperationResult object if successful. + */ + public KeyOperationResult encrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body(); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. + * + * @param vaultBaseUrl The vault name, for example 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> 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse encryptDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param vaultBaseUrl The vault name, for example 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 KeyOperationResult object if successful. + */ + public KeyOperationResult decrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body(); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Decrypts a single block of encrypted data. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse decryptDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Creates a signature from a digest using the specified key. + * + * @param vaultBaseUrl The vault name, for example 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 KeyOperationResult object if successful. + */ + public KeyOperationResult sign(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { + return signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body(); + } + + /** + * Creates a signature from a digest using the specified key. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key. + * @param keyVersion The version of the key. + * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param value the Base64Url value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Creates a signature from a digest using the specified key. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Creates a signature from a digest using the specified key. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key. + * @param keyVersion The version of the key. + * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> signWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + 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); + return service.sign(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = signDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse signDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Verifies a signature using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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 KeyVerifyResult object if successful. + */ + public KeyVerifyResult verify(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { + return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).toBlocking().single().body(); + } + + /** + * Verifies a signature using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature), serviceCallback); + } + + /** + * Verifies a signature using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Verifies a signature using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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> 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse verifyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Wraps a symmetric key using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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 KeyOperationResult object if successful. + */ + public KeyOperationResult wrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return wrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body(); + } + + /** + * Wraps a symmetric key using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(wrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Wraps a symmetric key using a specified key. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Wraps a symmetric key using a specified key. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key. + * @param keyVersion The version of the key. + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> wrapKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse wrapKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. + * + * @param vaultBaseUrl The vault name, for example 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 KeyOperationResult object if successful. + */ + public KeyOperationResult unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + return unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body(); + } + + /** + * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback); + } + + /** + * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param keyName The name of the key. + * @param keyVersion The version of the key. + * @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5' + * @param value the Base64Url value + * @return the observable to the KeyOperationResult object + */ + public Observable> unwrapKeyWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse unwrapKeyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param value The value of the secret. + * @return the SecretBundle object if successful. + */ + public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value) { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value).toBlocking().single().body(); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param value The value of the secret. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setSecretAsync(String vaultBaseUrl, String secretName, String value, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value), serviceCallback); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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); + } + } + }); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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 SecretBundle object if successful. + */ + public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes) { + return setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes).toBlocking().single().body(); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setSecretAsync(String vaultBaseUrl, String secretName, String value, Map tags, String contentType, SecretAttributes secretAttributes, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(setSecretWithServiceResponseAsync(vaultBaseUrl, secretName, value, tags, contentType, secretAttributes), serviceCallback); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * Sets a secret in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse setSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Deletes a secret from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @return the SecretBundle object if successful. + */ + public SecretBundle deleteSecret(String vaultBaseUrl, String secretName) { + return deleteSecretWithServiceResponseAsync(vaultBaseUrl, secretName).toBlocking().single().body(); + } + + /** + * Deletes a secret from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteSecretAsync(String vaultBaseUrl, String secretName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteSecretWithServiceResponseAsync(vaultBaseUrl, secretName), serviceCallback); + } + + /** + * Deletes a secret from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * Deletes a secret from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse deleteSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param secretVersion The version of the secret. + * @return the SecretBundle object if successful. + */ + public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion) { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single().body(); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param secretVersion The version of the secret. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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); + } + } + }); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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 SecretBundle object if successful. + */ + public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags) { + return updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags).toBlocking().single().body(); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, String contentType, SecretAttributes secretAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion, contentType, secretAttributes, tags), serviceCallback); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * Updates the attributes associated with a specified secret in a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse updateSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Get a specified secret from a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param secretVersion The version of the secret. + * @return the SecretBundle object if successful. + */ + public SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) { + return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).toBlocking().single().body(); + } + + /** + * Get a specified secret from a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param secretVersion The version of the secret. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); + } + + /** + * Get a specified secret from a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param secretVersion The version of the secret. + * @return the observable to the SecretBundle object + */ + 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.body(); + } + }); + } + + /** + * Get a specified secret from a given key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse getSecretDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @return the PagedList<SecretItem> object if successful. + */ + public PagedList getSecrets(final String vaultBaseUrl) { + ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getSecretsAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getSecretsSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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 PagedList<SecretItem> object if successful. + */ + public PagedList getSecrets(final String vaultBaseUrl, final Integer maxresults) { + ServiceResponse> response = getSecretsSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getSecretsAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getSecretsSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * List secrets in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List secrets in a specified key vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, for example 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."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getSecretsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @return the PagedList<SecretItem> object if successful. + */ + public PagedList getSecretVersions(final String vaultBaseUrl, final String secretName) { + ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body().nextPageLink(); + 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, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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 if successful. + */ + public PagedList getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) { + ServiceResponse> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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 ServiceFuture} object + */ + public ServiceFuture> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body(); + } + }); + } + + /** + * List the versions of the specified secret. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param secretName The name of the secret. + * @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.body().nextPageLink(); + 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, for example https://myvault.vault.azure.net. + ServiceResponse> * @param secretName The name of the secret. + 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getSecretVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @return the PagedList<CertificateItem> object if successful. + */ + public PagedList getCertificates(final String vaultBaseUrl) { + ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificatesAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getCertificatesSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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 PagedList<CertificateItem> object if successful. + */ + public PagedList getCertificates(final String vaultBaseUrl, final Integer maxresults) { + ServiceResponse> response = getCertificatesSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificatesAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getCertificatesSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * List certificates in a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificates in a specified key vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, for example 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."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getCertificatesDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Deletes a certificate from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @return the CertificateBundle object if successful. + */ + public CertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) { + return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); + } + + /** + * Deletes a certificate from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Deletes a certificate from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @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.body(); + } + }); + } + + /** + * Deletes a certificate from a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @return the observable to the CertificateBundle object + */ + public Observable> deleteCertificateWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse deleteCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Sets the certificate contacts for the specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param contacts The contacts for the key vault certificate. + * @return the Contacts object if successful. + */ + public Contacts setCertificateContacts(String vaultBaseUrl, Contacts contacts) { + return setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts).toBlocking().single().body(); + } + + /** + * Sets the certificate contacts for the specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param contacts The contacts for the key vault certificate. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts), serviceCallback); + } + + /** + * Sets the certificate contacts for the specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param contacts The contacts for the key vault certificate. + * @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.body(); + } + }); + } + + /** + * Sets the certificate contacts for the specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param contacts The contacts for the key vault certificate. + * @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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse setCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Lists the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @return the Contacts object if successful. + */ + public Contacts getCertificateContacts(String vaultBaseUrl) { + return getCertificateContactsWithServiceResponseAsync(vaultBaseUrl).toBlocking().single().body(); + } + + /** + * Lists the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); + } + + /** + * Lists the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Lists the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + private ServiceResponse getCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Deletes the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @return the Contacts object if successful. + */ + public Contacts deleteCertificateContacts(String vaultBaseUrl) { + return deleteCertificateContactsWithServiceResponseAsync(vaultBaseUrl).toBlocking().single().body(); + } + + /** + * Deletes the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); + } + + /** + * Deletes the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Deletes the certificate contacts for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + private ServiceResponse deleteCertificateContactsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @return the PagedList<CertificateIssuerItem> object if successful. + */ + public PagedList getCertificateIssuers(final String vaultBaseUrl) { + ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificateIssuersAsync(final String vaultBaseUrl, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getCertificateIssuersSinglePageAsync(vaultBaseUrl), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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 PagedList<CertificateIssuerItem> object if successful. + */ + public PagedList getCertificateIssuers(final String vaultBaseUrl, final Integer maxresults) { + ServiceResponse> response = getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificateIssuersAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificate issuers for a specified key vault. + * + ServiceResponse> * @param vaultBaseUrl The vault name, for example 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."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getCertificateIssuersDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param issuerName The name of the issuer. + * @param provider The issuer provider. + * @return the IssuerBundle object if successful. + */ + public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).toBlocking().single().body(); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider), serviceCallback); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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> 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 (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); + parameter.withProvider(provider); + parameter.withCredentials(null); + parameter.withOrganizationDetails(null); + parameter.withAttributes(null); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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, for example 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 IssuerBundle object if successful. + */ + public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { + return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single().body(); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Sets the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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> 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 (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + if (provider == null) { + throw new IllegalArgumentException("Parameter provider is required and cannot be null."); + } + Validator.validate(credentials); + Validator.validate(organizationDetails); + Validator.validate(attributes); + CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); + parameter.withProvider(provider); + parameter.withCredentials(credentials); + parameter.withOrganizationDetails(organizationDetails); + parameter.withAttributes(attributes); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + private ServiceResponse setCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param issuerName The name of the issuer. + * @return the IssuerBundle object if successful. + */ + public IssuerBundle updateCertificateIssuer(String vaultBaseUrl, String issuerName) { + return updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().body(); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param issuerName The name of the issuer. + * @return the observable to the IssuerBundle object + */ + 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 (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + final String provider = null; + final IssuerCredentials credentials = null; + final OrganizationDetails organizationDetails = null; + final IssuerAttributes attributes = null; + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(null); + parameter.withCredentials(null); + parameter.withOrganizationDetails(null); + parameter.withAttributes(null); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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, for example 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 IssuerBundle object if successful. + */ + public IssuerBundle updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { + return updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single().body(); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes), serviceCallback); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Updates the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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> 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 (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + Validator.validate(credentials); + Validator.validate(organizationDetails); + Validator.validate(attributes); + CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); + parameter.withProvider(provider); + parameter.withCredentials(credentials); + parameter.withOrganizationDetails(organizationDetails); + parameter.withAttributes(attributes); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + private ServiceResponse updateCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Lists the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param issuerName The name of the issuer. + * @return the IssuerBundle object if successful. + */ + public IssuerBundle getCertificateIssuer(String vaultBaseUrl, String issuerName) { + return getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().body(); + } + + /** + * Lists the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture getCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Lists the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Lists the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse getCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Deletes the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param issuerName The name of the issuer. + * @return the IssuerBundle object if successful. + */ + public IssuerBundle deleteCertificateIssuer(String vaultBaseUrl, String issuerName) { + return deleteCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).toBlocking().single().body(); + } + + /** + * Deletes the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName), serviceCallback); + } + + /** + * Deletes the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Deletes the specified certificate issuer. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse deleteCertificateIssuerDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @return the CertificateOperation object if successful. + */ + public CertificateOperation createCertificate(String vaultBaseUrl, String certificateName) { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture createCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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 CertificateOperation object if successful. + */ + public CertificateOperation createCertificate(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createCertificateAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Creates a new certificate. If this is the first version, the certificate resource is created. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse createCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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 CertificateBundle object if successful. + */ + public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate).toBlocking().single().body(); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate), serviceCallback); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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 CertificateBundle object if successful. + */ + public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. + * @param certificatePolicy The management policy for the certificate. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. + * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. + * @param certificatePolicy The management policy for the certificate. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the CertificateBundle object + */ + public Observable importCertificateAsync(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Imports a certificate into a specified key vault. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse importCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @return the PagedList<CertificateItem> object if successful. + */ + public PagedList getCertificateVersions(final String vaultBaseUrl, final String certificateName) { + ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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, for example 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.body(); + } + }); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + 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, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, for example 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 PagedList<CertificateItem> object if successful. + */ + public PagedList getCertificateVersions(final String vaultBaseUrl, final String certificateName, final Integer maxresults) { + ServiceResponse> response = getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, for example 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. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificateVersionsAsync(final String vaultBaseUrl, final String certificateName, final Integer maxresults, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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, for example 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.body(); + } + }); + } + + /** + * List the versions of a certificate. + * + * @param vaultBaseUrl The vault name, for example 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.body().nextPageLink(); + 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, for example 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."); + } + 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); + 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getCertificateVersionsDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Lists the policy for a certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in a given key vault. + * @return the CertificatePolicy object if successful. + */ + public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) { + return getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); + } + + /** + * Lists the policy for a certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in a given key vault. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getCertificatePolicyAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Lists the policy for a certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in a given key 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.body(); + } + }); + } + + /** + * Lists the policy for a certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in a given key 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse getCertificatePolicyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Updates the policy for a certificate. Set specified members in the certificate policy. Leave others as null. + * + * @param vaultBaseUrl The vault name, for example 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 CertificatePolicy object if successful. + */ + public CertificatePolicy updateCertificatePolicy(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy) { + return updateCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy).toBlocking().single().body(); + } + + /** + * Updates the policy for a certificate. Set specified members in the certificate policy. Leave others as null. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @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 ServiceFuture} object + */ + public ServiceFuture updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, CertificatePolicy certificatePolicy, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName, certificatePolicy), serviceCallback); + } + + /** + * Updates the policy for a certificate. Set specified members in the certificate policy. Leave others as null. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Updates the policy for a certificate. Set specified members in the certificate policy. Leave others as null. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse updateCertificatePolicyDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key vault. + * @param certificateVersion The version of the certificate. + * @return the CertificateBundle object if successful. + */ + public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single().body(); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key vault. + * @param certificateVersion The version of the certificate. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key 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.body(); + } + }); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key 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."); + } + if (certificateName == null) { + throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); + } + if (certificateVersion == null) { + throw new IllegalArgumentException("Parameter certificateVersion is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + final CertificatePolicy certificatePolicy = null; + final CertificateAttributes certificateAttributes = null; + final Map tags = null; + CertificateUpdateParameters parameters = new CertificateUpdateParameters(); + parameters.withCertificatePolicy(null); + parameters.withCertificateAttributes(null); + parameters.withTags(null); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key 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 CertificateBundle object if successful. + */ + public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key 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 ServiceFuture} object + */ + public ServiceFuture updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags), serviceCallback); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key vault. + * @param certificateVersion The version of the certificate. + * @param certificatePolicy The management policy for the certificate. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the CertificateBundle object + */ + public Observable updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { + return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the specified attributes associated with the given certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate in the given key vault. + * @param certificateVersion The version of the certificate. + * @param certificatePolicy The management policy for the certificate. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the CertificateBundle object + */ + public Observable> 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."); + } + if (certificateName == null) { + throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); + } + if (certificateVersion == null) { + throw new IllegalArgumentException("Parameter certificateVersion is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + Validator.validate(certificatePolicy); + Validator.validate(certificateAttributes); + Validator.validate(tags); + CertificateUpdateParameters parameters = new CertificateUpdateParameters(); + parameters.withCertificatePolicy(certificatePolicy); + parameters.withCertificateAttributes(certificateAttributes); + parameters.withTags(tags); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + private ServiceResponse updateCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Gets information about a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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 CertificateBundle object if successful. + */ + public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) { + return getCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion).toBlocking().single().body(); + } + + /** + * Gets information about a specified certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @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 ServiceFuture} object + */ + public ServiceFuture getCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback); + } + + /** + * Gets information about a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Gets information about a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse getCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Updates a certificate operation. + * + * @param vaultBaseUrl The vault name, for example 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 CertificateOperation object if successful. + */ + public CertificateOperation updateCertificateOperation(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { + return updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested).toBlocking().single().body(); + } + + /** + * Updates a certificate operation. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested), serviceCallback); + } + + /** + * Updates a certificate operation. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Updates a certificate operation. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. + * @return the observable to the CertificateOperation object + */ + public Observable> updateCertificateOperationWithServiceResponseAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) { + if (vaultBaseUrl == null) { + throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); + } + if (certificateName == null) { + throw new IllegalArgumentException("Parameter certificateName is required and cannot be null."); + } + if (this.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); + } + CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); + certificateOperation.withCancellationRequested(cancellationRequested); + String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); + 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); + } + } + }); + } + + private ServiceResponse updateCertificateOperationDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Gets the operation associated with a specified certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @return the CertificateOperation object if successful. + */ + public CertificateOperation getCertificateOperation(String vaultBaseUrl, String certificateName) { + return getCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); + } + + /** + * Gets the operation associated with a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture getCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Gets the operation associated with a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Gets the operation associated with a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse getCertificateOperationDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Deletes the operation for a specified certificate. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @return the CertificateOperation object if successful. + */ + public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) { + return deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); + } + + /** + * Deletes the operation for a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback); + } + + /** + * Deletes the operation for a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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.body(); + } + }); + } + + /** + * Deletes the operation for a specified certificate. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse deleteCertificateOperationDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param x509Certificates The certificate or the certificate chain to merge. + * @return the CertificateBundle object if successful. + */ + public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates) { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates).toBlocking().single().body(); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @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 ServiceFuture} object + */ + public ServiceFuture mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(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, for example 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.body(); + } + }); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example 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."); + } + 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); + 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); + } + } + }); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param x509Certificates The certificate or the certificate chain to merge. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @return the CertificateBundle object if successful. + */ + public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags).toBlocking().single().body(); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example 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 ServiceFuture} object + */ + public ServiceFuture mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags), serviceCallback); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param x509Certificates The certificate or the certificate chain to merge. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the CertificateBundle object + */ + public Observable mergeCertificateAsync(String vaultBaseUrl, String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { + return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, tags).map(new Func1, CertificateBundle>() { + @Override + public CertificateBundle call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Merges a certificate or a certificate chain with a key pair existing on the server. + * + * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * @param certificateName The name of the certificate. + * @param x509Certificates The certificate or the certificate chain to merge. + * @param certificateAttributes The attributes of the certificate (optional). + * @param tags Application specific metadata in the form of key-value pairs. + * @return the observable to the CertificateBundle object + */ + public Observable> 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."); + } + 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); + 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); + } + } + }); + } + + private ServiceResponse mergeCertificateDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory().newInstance(this.serializerAdapter()) + .register(201, new TypeToken() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<KeyItem> object if successful. + */ + public PagedList getKeyVersionsNext(final String nextPageLink) { + ServiceResponse> response = getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getKeyVersionsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getKeyVersionsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getKeyVersionsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @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.body(); + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + * @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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getKeyVersionsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. + * + 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getKeyVersionsNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getKeyVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List keys in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<KeyItem> object if successful. + */ + public PagedList getKeysNext(final String nextPageLink) { + ServiceResponse> response = getKeysNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getKeysNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List keys in the specified vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getKeysNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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.body(); + } + }); + } + + /** + * 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.body().nextPageLink(); + 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getKeysNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getKeysNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List secrets in a specified key vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<SecretItem> object if successful. + */ + public PagedList getSecretsNext(final String nextPageLink) { + ServiceResponse> response = getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List secrets in a specified key vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getSecretsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getSecretsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getSecretsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List secrets in a specified key 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.body(); + } + }); + } + + /** + * List secrets in a specified key 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getSecretsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List secrets in a specified key 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getSecretsNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getSecretsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List the versions of the specified secret. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<SecretItem> object if successful. + */ + public PagedList getSecretVersionsNext(final String nextPageLink) { + ServiceResponse> response = getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List the versions of the specified secret. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getSecretVersionsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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.body(); + } + }); + } + + /** + * 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.body().nextPageLink(); + 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getSecretVersionsNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getSecretVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List certificates in a specified key vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<CertificateItem> object if successful. + */ + public PagedList getCertificatesNext(final String nextPageLink) { + ServiceResponse> response = getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List certificates in a specified key vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificatesNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getCertificatesNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificates in a specified key 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.body(); + } + }); + } + + /** + * List certificates in a specified key 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificates in a specified key 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getCertificatesNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getCertificatesNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List certificate issuers for a specified key vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<CertificateIssuerItem> object if successful. + */ + public PagedList getCertificateIssuersNext(final String nextPageLink) { + ServiceResponse> response = getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List certificate issuers for a specified key vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificateIssuersNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + getCertificateIssuersNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return getCertificateIssuersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * List certificate issuers for a specified key 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.body(); + } + }); + } + + /** + * List certificate issuers for a specified key 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.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * List certificate issuers for a specified key 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getCertificateIssuersNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getCertificateIssuersNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + + /** + * List the versions of a certificate. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<CertificateItem> object if successful. + */ + public PagedList getCertificateVersionsNext(final String nextPageLink) { + ServiceResponse> response = getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return getCertificateVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * List the versions of a certificate. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceCall object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> getCertificateVersionsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + 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.body(); + } + }); + } + + /** + * 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.body().nextPageLink(); + 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."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.getCertificateVersionsNext(nextUrl, 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.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> getCertificateVersionsNextDelegate(Response response) throws KeyVaultErrorException, IOException, IllegalArgumentException { + return this.restClient().responseBuilderFactory()., KeyVaultErrorException>newInstance(this.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(KeyVaultErrorException.class) + .build(response); + } + +} 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 new file mode 100755 index 000000000000..e026b82b7d9a --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java @@ -0,0 +1,222 @@ +/** + * 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; + +import java.net.URI; +import java.net.URISyntaxException; +import java.security.InvalidParameterException; + +/** + * The key vault object identifier. + */ +public class ObjectIdentifier { + + /** + * Verifies whether the identifier belongs to a key vault object. + * @param collection the object collection e.g. 'keys', 'secrets' and 'certificates'. + * @param identifier the key vault object identifier. + * @return true if the identifier belongs to a key vault object. False otherwise. + */ + protected static boolean isObjectIdentifier(String collection, String identifier) { + + collection = verifyNonEmpty(collection, "collection"); + identifier = verifyNonEmpty(identifier, "identifier"); + + URI baseUri; + try { + baseUri = new URI(identifier); + } catch (URISyntaxException e) { + return false; + } + + // Path is of the form "/collection/name[/version]" + String[] segments = baseUri.getPath().split("/"); + if (segments.length != 3 && segments.length != 4) { + return false; + } + + if (!collection.equals(segments[1])) { + return false; + } + + return true; + } + + /** + * Verifies a value is null or empty. Returns the value if non-empty and throws exception if empty. + * @param value the value to verify. + * @param argName the name of the value. + * @return Returns the value if non-empty. + */ + protected static String verifyNonEmpty(String value, String argName) { + if (value != null) { + value = value.trim(); + if (value.isEmpty()) { + value = null; + } + } + if (value == null) { + throw new IllegalArgumentException(argName); + } + return value; + } + + protected String vault; + protected String name; + protected String version; + protected String baseIdentifier; + protected String identifier; + + /** + * Constructor. + */ + protected ObjectIdentifier() { + } + + /** + * Constructor. + * @param vault the vault url. + * @param collection the object collection name. e.g. 'keys', 'secrets' and 'certificates'. + * @param name the object name. + */ + protected ObjectIdentifier(String vault, String collection, String name) { + this(vault, collection, name, null); + } + + /** + * Constructor. + * @param vault the vault url. + * @param collection the object collection name. e.g. 'keys', 'secrets' and 'certificates'. + * @param name the object name. + * @param version the object version. + */ + protected ObjectIdentifier(String vault, String collection, String name, String version) { + + vault = verifyNonEmpty(vault, "vault"); + collection = verifyNonEmpty(collection, "collection"); + name = verifyNonEmpty(name, "name"); + + if (version != null) { + version = version.trim(); + } else { + version = ""; + } + + URI baseUri; + try { + baseUri = new URI(vault); + } catch (URISyntaxException e) { + throw new InvalidParameterException(String.format("Invalid ObjectIdentifier: %s. Not a valid URI", vault)); + } + + this.name = name; + this.version = version; + this.vault = String.format("%s://%s", baseUri.getScheme(), getFullAuthority(baseUri)); + baseIdentifier = String.format("%s/%s/%s", this.vault, collection, this.name); + identifier = (version == null || version.isEmpty()) ? baseIdentifier + : String.format("%s/%s", baseIdentifier, version); + } + + /** + * Constructor. + * @param collection the object collection name. e.g. 'keys', 'secrets' and 'certificates'. + * @param identifier the object identifier. + */ + protected ObjectIdentifier(String collection, String identifier) { + + if (collection == null || collection.length() == 0) { + throw new IllegalArgumentException("collection"); + } + + if (identifier == null || identifier.length() == 0) { + throw new IllegalArgumentException("identifier"); + } + + URI baseUri; + try { + baseUri = new URI(identifier); + } catch (URISyntaxException e) { + throw new InvalidParameterException( + String.format("Invalid ObjectIdentifier: %s. Not a valid URI", identifier)); + } + + // Path is of the form "/collection/name[/version]" + String[] segments = baseUri.getPath().split("/"); + if (segments.length != 3 && segments.length != 4) { + throw new InvalidParameterException(String + .format("Invalid ObjectIdentifier: %s. Bad number of segments: %d", identifier, segments.length)); + } + + if (!collection.equals(segments[1])) { + throw new InvalidParameterException( + String.format("Invalid ObjectIdentifier: %s. segment [1] should be '%s', found '%s'", identifier, + collection, segments[1])); + } + + name = segments[2]; + version = segments.length == 4 ? segments[3] : null; + vault = String.format("%s://%s", baseUri.getScheme(), getFullAuthority(baseUri)); + baseIdentifier = String.format("%s/%s/%s", vault, collection, name); + this.identifier = (version == null || version.equals("")) ? baseIdentifier + : String.format("%s/%s", baseIdentifier, version); + } + + /** + * Gets full authority for a URL by appending port to the url authority. + * @param uri the URL to get the full authority for. + * @return the full authority. + */ + protected String getFullAuthority(URI uri) { + String authority = uri.getAuthority(); + if (!authority.contains(":") && uri.getPort() > 0) { + // Append port for complete authority + authority = String.format("%s:%d", uri.getAuthority(), uri.getPort()); + } + return authority; + } + + /** + * @return The base identifier for an object, does not include the object + * version. + */ + public String baseIdentifier() { + return baseIdentifier; + } + + /** + * @return The identifier for an object, includes the objects version. + */ + public String identifier() { + return identifier; + } + + /** + * @return The name of the object. + */ + public String name() { + return name; + } + + /** + * @return The vault containing the object. + */ + public String vault() { + return vault; + } + + /** + * @return The version of the object. + */ + public String version() { + return version; + } + + @Override + public String toString() { + return identifier; + } +} 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 new file mode 100755 index 000000000000..c2564685eb82 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java @@ -0,0 +1,49 @@ +/** + * 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; + +/** + * Key Vault secret identifier. + */ +public final class SecretIdentifier extends ObjectIdentifier { + + /** + * Verifies whether the identifier belongs to a key vault secret. + * @param identifier the key vault secret identifier. + * @return true if the identifier belongs to a key vault secret. False otherwise. + */ + public static boolean isSecretIdentifier(String identifier) { + return ObjectIdentifier.isObjectIdentifier("secrets", identifier); + } + + /** + * Constructor. + * @param vault the vault url. + * @param name the name of secret. + */ + public SecretIdentifier(String vault, String name) { + this(vault, name, ""); + } + + /** + * Constructor. + * @param vault the vault url. + * @param name the name of secret. + * @param version the secret version. + */ + public SecretIdentifier(String vault, String name, String version) { + super(vault, "secrets", name, version); + } + + /** + * Constructor. + * @param identifier the object identifier. + */ + public SecretIdentifier(String identifier) { + super("secrets", identifier); + } +} 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 new file mode 100755 index 000000000000..a0700600afff --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java @@ -0,0 +1,76 @@ +/** + * 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; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import okhttp3.HttpUrl; + +/** + * Handles caching of the challenge. + */ +class ChallengeCache { + + private final HashMap> cachedChallenges = new HashMap>(); + + /** + * Uses authority to retrieve the cached values. + * + * @param url + * the url that is used as a cache key. + * @return cached value or null if value is not available. + */ + public Map getCachedChallenge(HttpUrl url) { + if (url == null) { + return null; + } + String authority = getAuthority(url); + authority = authority.toLowerCase(Locale.ENGLISH); + return cachedChallenges.get(authority); + } + + /** + * Uses authority to cache challenge. + * + * @param url + * the url that is used as a cache key. + * @param challenge + * the challenge to cache. + */ + public void addCachedChallenge(HttpUrl url, Map challenge) { + if (url == null || challenge == null) { + return; + } + String authority = getAuthority(url); + authority = authority.toLowerCase(Locale.ENGLISH); + cachedChallenges.put(authority, challenge); + } + + /** + * Gets authority of a url. + * + * @param url + * the url to get the authority for. + * @return the authority. + */ + public String getAuthority(HttpUrl url) { + String scheme = url.scheme(); + String host = url.host(); + int port = url.port(); + StringBuilder builder = new StringBuilder(); + if (scheme != null) { + builder.append(scheme).append("://"); + } + builder.append(host); + if (port >= 0) { + builder.append(':').append(port); + } + return builder.toString(); + } +} 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 new file mode 100755 index 000000000000..b10d3a6c287b --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java @@ -0,0 +1,218 @@ +/** + * 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; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.microsoft.rest.credentials.ServiceClientCredentials; + +import okhttp3.Authenticator; +import okhttp3.HttpUrl; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.Route; + +/** + * An implementation of {@link ServiceClientCredentials} that supports automatic bearer token refresh. + * + */ +public abstract class KeyVaultCredentials implements ServiceClientCredentials { + + private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; + private static final String AUTHENTICATE = "Authorization"; + private static final String BEARER_TOKEP_REFIX = "Bearer "; + + private final ChallengeCache cache = new ChallengeCache(); + + @Override + public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { + + clientBuilder.addInterceptor(new Interceptor() { + + @Override + public Response intercept(Chain chain) throws IOException { + + HttpUrl url = chain.request().url(); + + Map challengeMap = cache.getCachedChallenge(url); + + if (challengeMap != null) { + // Get the bearer token + String credential = getAuthenticationCredentials(challengeMap); + + Request newRequest = chain.request().newBuilder() + .header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build(); + + return chain.proceed(newRequest); + } else { + // challenge is new for the URL and is not cached, + // so the request is sent out to get the challenges in + // response + return chain.proceed(chain.request()); + } + } + }); + + // Caches the challenge for failed request and re-send the request with + // access token. + clientBuilder.authenticator(new Authenticator() { + + @Override + public Request authenticate(Route route, Response response) throws IOException { + + // if challenge is not cached then extract and cache it + String authenticateHeader = response.header(WWW_AUTHENTICATE); + + Map challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX); + + // Cache the challenge + cache.addCachedChallenge(response.request().url(), challengeMap); + + // Get the bearer token from the callback by providing the + // challenges + String credential = getAuthenticationCredentials(challengeMap); + + if (credential == null) { + return null; + } + + // Add the token header and resume the call. + // The token should live for duration of this request and never + // be cached anywhere in our code. + return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build(); + } + }); + } + + /** + * Extracts the authentication challenges from the challenge map and calls + * the authentication callback to get the bearer token and return it. + * + * @param challengeMap + * the challenge map. + * @return the bearer token. + */ + private String getAuthenticationCredentials(Map challengeMap) { + + String authorization = challengeMap.get("authorization"); + if (authorization == null) { + authorization = challengeMap.get("authorization_uri"); + } + + String resource = challengeMap.get("resource"); + String scope = challengeMap.get("scope"); + + return doAuthenticate(authorization, resource, scope); + } + + /** + * Extracts the challenge off the authentication header. + * + * @param authenticateHeader + * the authentication header containing all the challenges. + * @param authChallengePrefix + * the authentication challenge name. + * @return a challenge map. + */ + private static Map extractChallenge(String authenticateHeader, String authChallengePrefix) { + if (!isValidChallenge(authenticateHeader, authChallengePrefix)) { + return null; + } + + authenticateHeader = authenticateHeader.toLowerCase().replace(authChallengePrefix.toLowerCase(), ""); + + String[] challenges = authenticateHeader.split(", "); + Map challengeMap = new HashMap(); + for (String pair : challenges) { + String[] keyValue = pair.split("="); + challengeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); + } + return challengeMap; + } + + /** + * Verifies whether a challenge is bearer or not. + * + * @param authenticateHeader + * the authentication header containing all the challenges. + * @param authChallengePrefix + * the authentication challenge name. + * @return + */ + private static boolean isValidChallenge(String authenticateHeader, String authChallengePrefix) { + if (authenticateHeader != null && !authenticateHeader.isEmpty() + && authenticateHeader.toLowerCase().startsWith(authChallengePrefix.toLowerCase())) { + return true; + } + return false; + } + + /** + * Abstract method to be implemented. + * + * @param authorization + * Identifier of the authority, a URL. + * @param resource + * Identifier of the target resource that is the recipient of the + * requested token, a URL. + * @param scope + * The scope of the authentication request. + * + * @return The access token + * + * Answers a server challenge with a token header. + *

+ * Implementations typically use ADAL to get a token, as performed + * in the sample below: + *

+ * + *
+     * @Override
+     * public String doAuthenticate(String authorization, String resource, String scope) {
+     *     String clientId = ...; // client GUID as shown in Azure portal.
+     *     String clientKey = ...; // client key as provided by Azure portal.
+     *     AuthenticationResult token = getAccessTokenFromClientCredentials(authorization, resource, clientId, clientKey);
+     *     return token.getAccessToken();;
+     * }
+     *
+     * private static AuthenticationResult getAccessTokenFromClientCredentials(String authorization, String resource, String clientId, String clientKey) {
+     *     AuthenticationContext context = null;
+     *     AuthenticationResult result = null;
+     *     ExecutorService service = null;
+     *     try {
+     *         service = Executors.newFixedThreadPool(1);
+     *         context = new AuthenticationContext(authorization, false, service);
+     *         ClientCredential credentials = new ClientCredential(clientId, clientKey);
+     *         Future<AuthenticationResult> future = context.acquireToken(resource, credentials, null);
+     *         result = future.get();
+     *     } catch (Exception e) {
+     *         throw new RuntimeException(e);
+     *     } finally {
+     *         service.shutdown();
+     *     }
+     *
+     *     if (result == null) {
+     *         throw new RuntimeException("authentication result was null");
+     *     }
+     *     return result;
+     * }
+     *         
+ * + *

+ * Note: The client key must be securely stored. It's advised to + * use two client applications - one for development and other for + * production - managed by separate parties. + *

+ * + */ + public abstract String doAuthenticate(String authorization, String resource, String scope); + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java new file mode 100755 index 000000000000..8b2adca34c71 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/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 the classes for KeyVaultClient. Performs cryptographic + * key operations and vault operations against the Key Vault service. + */ +package com.microsoft.azure.keyvault.authentication; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java new file mode 100755 index 000000000000..1f70881a0e84 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java @@ -0,0 +1,46 @@ +/** + * 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 1.0.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 action that will be executed. + */ +public class Action { + /** + * The type of the action. Possible values include: 'EmailContacts', + * 'AutoRenew'. + */ + @JsonProperty(value = "action_type") + private ActionType actionType; + + /** + * Get the actionType value. + * + * @return the actionType value + */ + public ActionType actionType() { + return this.actionType; + } + + /** + * Set the actionType value. + * + * @param actionType the actionType value to set + * @return the Action object itself. + */ + public Action withActionType(ActionType actionType) { + this.actionType = actionType; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java new file mode 100755 index 000000000000..9ec938c16e3f --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java @@ -0,0 +1,55 @@ +/** + * 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 1.0.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.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for ActionType. + */ +public enum ActionType { + /** Enum value EmailContacts. */ + EMAIL_CONTACTS("EmailContacts"), + + /** Enum value AutoRenew. */ + AUTO_RENEW("AutoRenew"); + + /** The actual serialized value for a ActionType instance. */ + private String value; + + ActionType(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a ActionType instance. + * + * @param value the serialized value to parse. + * @return the parsed ActionType object, or null if unable to parse. + */ + @JsonCreator + public static ActionType fromString(String value) { + ActionType[] items = ActionType.values(); + for (ActionType item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java new file mode 100755 index 000000000000..0e60e9cf8e32 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java @@ -0,0 +1,123 @@ +/** + * 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 1.0.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; + +/** + * Details of the organization administrator of the certificate issuer. + */ +public class AdministratorDetails { + /** + * First name. + */ + @JsonProperty(value = "first_name") + private String firstName; + + /** + * Last name. + */ + @JsonProperty(value = "last_name") + private String lastName; + + /** + * Email addresss. + */ + @JsonProperty(value = "email") + private String emailAddress; + + /** + * Phone number. + */ + @JsonProperty(value = "phone") + private String phone; + + /** + * Get the firstName value. + * + * @return the firstName value + */ + public String firstName() { + return this.firstName; + } + + /** + * Set the firstName value. + * + * @param firstName the firstName value to set + * @return the AdministratorDetails object itself. + */ + public AdministratorDetails withFirstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get the lastName value. + * + * @return the lastName value + */ + public String lastName() { + return this.lastName; + } + + /** + * Set the lastName value. + * + * @param lastName the lastName value to set + * @return the AdministratorDetails object itself. + */ + public AdministratorDetails withLastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get the emailAddress value. + * + * @return the emailAddress value + */ + public String emailAddress() { + return this.emailAddress; + } + + /** + * Set the emailAddress value. + * + * @param emailAddress the emailAddress value to set + * @return the AdministratorDetails object itself. + */ + public AdministratorDetails withEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + return this; + } + + /** + * Get the phone value. + * + * @return the phone value + */ + public String phone() { + return this.phone; + } + + /** + * Set the phone value. + * + * @param phone the phone value to set + * @return the AdministratorDetails object itself. + */ + public AdministratorDetails withPhone(String phone) { + this.phone = phone; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java new file mode 100755 index 000000000000..d4028e2176d0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java @@ -0,0 +1,149 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The object attributes managed by the KeyVault service. + */ +public class Attributes { + /** + * Determines whether the object is enabled. + */ + @JsonProperty(value = "enabled") + private Boolean enabled; + + /** + * Not before date in UTC. + */ + @JsonProperty(value = "nbf") + private Long notBefore; + + /** + * Expiry date in UTC. + */ + @JsonProperty(value = "exp") + private Long expires; + + /** + * Creation time in UTC. + */ + @JsonProperty(value = "created", access = JsonProperty.Access.WRITE_ONLY) + private Long created; + + /** + * Last updated time in UTC. + */ + @JsonProperty(value = "updated", access = JsonProperty.Access.WRITE_ONLY) + private Long updated; + + /** + * Get the enabled value. + * + * @return the enabled value + */ + public Boolean enabled() { + return this.enabled; + } + + /** + * Set the enabled value. + * + * @param enabled the enabled value to set + * @return the Attributes object itself. + */ + public Attributes withEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Get the notBefore value. + * + * @return the notBefore value + */ + public DateTime notBefore() { + if (this.notBefore == null) { + return null; + } + return new DateTime(this.notBefore * 1000L, DateTimeZone.UTC); + } + + /** + * Set the notBefore value. + * + * @param notBefore the notBefore value to set + * @return the Attributes object itself. + */ + public Attributes withNotBefore(DateTime notBefore) { + if (notBefore == null) { + this.notBefore = null; + } else { + this.notBefore = notBefore.toDateTime(DateTimeZone.UTC).getMillis() / 1000; + } + return this; + } + + /** + * Get the expires value. + * + * @return the expires value + */ + public DateTime expires() { + if (this.expires == null) { + return null; + } + return new DateTime(this.expires * 1000L, DateTimeZone.UTC); + } + + /** + * Set the expires value. + * + * @param expires the expires value to set + * @return the Attributes object itself. + */ + public Attributes withExpires(DateTime expires) { + if (expires == null) { + this.expires = null; + } else { + this.expires = expires.toDateTime(DateTimeZone.UTC).getMillis() / 1000; + } + return this; + } + + /** + * Get the created value. + * + * @return the created value + */ + public DateTime created() { + if (this.created == null) { + return null; + } + return new DateTime(this.created * 1000L, DateTimeZone.UTC); + } + + /** + * Get the updated value. + * + * @return the updated value + */ + public DateTime updated() { + if (this.updated == null) { + return null; + } + return new DateTime(this.updated * 1000L, DateTimeZone.UTC); + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java new file mode 100755 index 000000000000..9efe5dba7225 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.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. + * + * Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The backup key result, containing the backup blob. + */ +public class BackupKeyResult { + /** + * The backup blob containing the backed up key. + */ + @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY) + private Base64Url value; + + /** + * Get the value value. + * + * @return the value value + */ + public byte[] value() { + if (this.value == null) { + return null; + } + return this.value.decodedBytes(); + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java new file mode 100755 index 000000000000..96dcea18189d --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java @@ -0,0 +1,18 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + + +/** + * The certificate management attributes. + */ +public class CertificateAttributes extends Attributes { +} 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 new file mode 100755 index 000000000000..524885a86230 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java @@ -0,0 +1,257 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.azure.keyvault.CertificateIdentifier; +import com.microsoft.azure.keyvault.KeyIdentifier; +import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.rest.Base64Url; + +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; + +/** + * A certificate bundle consists of a certificate (X509) plus its attributes. + */ +public class CertificateBundle { + /** + * The certificate id. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * The key id. + */ + @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) + private String kid; + + /** + * The secret id. + */ + @JsonProperty(value = "sid", access = JsonProperty.Access.WRITE_ONLY) + private String sid; + + /** + * Thumbprint of the certificate. + */ + @JsonProperty(value = "x5t", access = JsonProperty.Access.WRITE_ONLY) + private Base64Url x509Thumbprint; + + /** + * The management policy. + */ + @JsonProperty(value = "policy", access = JsonProperty.Access.WRITE_ONLY) + private CertificatePolicy policy; + + /** + * CER contents of x509 certificate. + */ + @JsonProperty(value = "cer") + private byte[] cer; + + /** + * The content type of the secret. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /** + * The certificate attributes. + */ + @JsonProperty(value = "attributes") + private CertificateAttributes attributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get the kid value. + * + * @return the kid value + */ + public String kid() { + return this.kid; + } + + /** + * Get the sid value. + * + * @return the sid value + */ + public String sid() { + return this.sid; + } + + /** + * Get the x509Thumbprint value. + * + * @return the x509Thumbprint value + */ + public byte[] x509Thumbprint() { + if (this.x509Thumbprint == null) { + return null; + } + return this.x509Thumbprint.decodedBytes(); + } + + /** + * Get the policy value. + * + * @return the policy value + */ + public CertificatePolicy policy() { + return this.policy; + } + + /** + * Get the cer value. + * + * @return the cer value + */ + public byte[] cer() { + return this.cer; + } + + /** + * Set the cer value. + * + * @param cer the cer value to set + * @return the CertificateBundle object itself. + */ + public CertificateBundle withCer(byte[] cer) { + this.cer = cer; + return this; + } + + /** + * Get the contentType value. + * + * @return the contentType value + */ + public String contentType() { + return this.contentType; + } + + /** + * Set the contentType value. + * + * @param contentType the contentType value to set + * @return the CertificateBundle object itself. + */ + public CertificateBundle withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public CertificateAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the CertificateBundle object itself. + */ + public CertificateBundle withAttributes(CertificateAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the CertificateBundle object itself. + */ + public CertificateBundle withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * The certificate identifier. + * @return certificate identifier + */ + public CertificateIdentifier certificateIdentifier() { + if (id() == null || id().isEmpty()) { + return null; + } + return new CertificateIdentifier(id()); + } + + /** + * The secret identifier. + * @return secret identifier + */ + public SecretIdentifier secretIdentifier() { + if (sid() == null || sid().isEmpty()) { + return null; + } + return new SecretIdentifier(sid()); + } + + /** + * The key identifier. + * @return key identifier + */ + public KeyIdentifier keyIdentifier() { + if (kid() == null || kid().isEmpty()) { + return null; + } + return new KeyIdentifier(kid()); + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java new file mode 100755 index 000000000000..313ea1007b89 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java @@ -0,0 +1,98 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The certificate create parameters. + */ +public class CertificateCreateParameters { + /** + * The management policy for the certificate. + */ + @JsonProperty(value = "policy") + private CertificatePolicy certificatePolicy; + + /** + * The attributes of the certificate (optional). + */ + @JsonProperty(value = "attributes") + private CertificateAttributes certificateAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + 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 CertificateCreateParameters object itself. + */ + public CertificateCreateParameters withCertificatePolicy(CertificatePolicy certificatePolicy) { + this.certificatePolicy = certificatePolicy; + return this; + } + + /** + * Get the certificateAttributes value. + * + * @return the certificateAttributes value + */ + public CertificateAttributes certificateAttributes() { + return this.certificateAttributes; + } + + /** + * Set the certificateAttributes value. + * + * @param certificateAttributes the certificateAttributes value to set + * @return the CertificateCreateParameters object itself. + */ + public CertificateCreateParameters withCertificateAttributes(CertificateAttributes certificateAttributes) { + this.certificateAttributes = certificateAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the CertificateCreateParameters object itself. + */ + public CertificateCreateParameters withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java new file mode 100755 index 000000000000..a85509ce874e --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java @@ -0,0 +1,152 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The certificate import parameters. + */ +public class CertificateImportParameters { + /** + * Base64 encoded representation of the certificate object to import. This + * certificate needs to contain the private key. + */ + @JsonProperty(value = "value", required = true) + private String base64EncodedCertificate; + + /** + * If the private key in base64EncodedCertificate is encrypted, the + * password used for encryption. + */ + @JsonProperty(value = "pwd") + private String password; + + /** + * The management policy for the certificate. + */ + @JsonProperty(value = "policy") + private CertificatePolicy certificatePolicy; + + /** + * The attributes of the certificate (optional). + */ + @JsonProperty(value = "attributes") + private CertificateAttributes certificateAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the base64EncodedCertificate value. + * + * @return the base64EncodedCertificate value + */ + public String base64EncodedCertificate() { + return this.base64EncodedCertificate; + } + + /** + * Set the base64EncodedCertificate value. + * + * @param base64EncodedCertificate the base64EncodedCertificate value to set + * @return the CertificateImportParameters object itself. + */ + public CertificateImportParameters withBase64EncodedCertificate(String base64EncodedCertificate) { + this.base64EncodedCertificate = base64EncodedCertificate; + return this; + } + + /** + * Get the password value. + * + * @return the password value + */ + public String password() { + return this.password; + } + + /** + * Set the password value. + * + * @param password the password value to set + * @return the CertificateImportParameters object itself. + */ + public CertificateImportParameters withPassword(String password) { + this.password = password; + return this; + } + + /** + * 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 CertificateImportParameters object itself. + */ + public CertificateImportParameters withCertificatePolicy(CertificatePolicy certificatePolicy) { + this.certificatePolicy = certificatePolicy; + return this; + } + + /** + * Get the certificateAttributes value. + * + * @return the certificateAttributes value + */ + public CertificateAttributes certificateAttributes() { + return this.certificateAttributes; + } + + /** + * Set the certificateAttributes value. + * + * @param certificateAttributes the certificateAttributes value to set + * @return the CertificateImportParameters object itself. + */ + public CertificateImportParameters withCertificateAttributes(CertificateAttributes certificateAttributes) { + this.certificateAttributes = certificateAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the CertificateImportParameters object itself. + */ + public CertificateImportParameters withTags(Map tags) { + this.tags = tags; + return this; + } + +} 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 new file mode 100755 index 000000000000..58fd49c03aff --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java @@ -0,0 +1,71 @@ +/** + * 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 1.0.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 item containing certificate issuer metadata. + */ +public class CertificateIssuerItem { + /** + * Certificate Identifier. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The issuer provider. + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the id value. + * + * @param id the id value to set + * @return the CertificateIssuerItem object itself. + */ + public CertificateIssuerItem withId(String id) { + this.id = id; + return this; + } + + /** + * 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 CertificateIssuerItem object itself. + */ + public CertificateIssuerItem withProvider(String provider) { + this.provider = provider; + return this; + } + +} 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 000000000000..629ae3db2924 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java @@ -0,0 +1,123 @@ +/** + * 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 1.0.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(value = "provider", required = true) + private String provider; + + /** + * The credentials to be used for the issuer. + */ + @JsonProperty(value = "credentials") + private IssuerCredentials credentials; + + /** + * Details of the organization as provided to the issuer. + */ + @JsonProperty(value = "org_details") + private OrganizationDetails organizationDetails; + + /** + * Attributes of the issuer object. + */ + @JsonProperty(value = "attributes") + 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 000000000000..799634b153cd --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java @@ -0,0 +1,123 @@ +/** + * 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 1.0.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. + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * The credentials to be used for the issuer. + */ + @JsonProperty(value = "credentials") + private IssuerCredentials credentials; + + /** + * Details of the organization as provided to the issuer. + */ + @JsonProperty(value = "org_details") + private OrganizationDetails organizationDetails; + + /** + * Attributes of the issuer object. + */ + @JsonProperty(value = "attributes") + 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/CertificateItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java new file mode 100755 index 000000000000..e190bc8b024b --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java @@ -0,0 +1,146 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.microsoft.azure.keyvault.CertificateIdentifier; +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The certificate item containing certificate metadata. + */ +public class CertificateItem { + /** + * Certificate identifier. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The certificate management attributes. + */ + @JsonProperty(value = "attributes") + private CertificateAttributes attributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Thumbprint of the certificate. + */ + @JsonProperty(value = "x5t") + private Base64Url x509Thumbprint; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the id value. + * + * @param id the id value to set + * @return the CertificateItem object itself. + */ + public CertificateItem withId(String id) { + this.id = id; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public CertificateAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the CertificateItem object itself. + */ + public CertificateItem withAttributes(CertificateAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the CertificateItem object itself. + */ + public CertificateItem withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the x509Thumbprint value. + * + * @return the x509Thumbprint value + */ + public byte[] x509Thumbprint() { + if (this.x509Thumbprint == null) { + return null; + } + return this.x509Thumbprint.decodedBytes(); + } + + /** + * Set the x509Thumbprint value. + * + * @param x509Thumbprint the x509Thumbprint value to set + * @return the CertificateItem object itself. + */ + public CertificateItem withX509Thumbprint(byte[] x509Thumbprint) { + if (x509Thumbprint == null) { + this.x509Thumbprint = null; + } else { + this.x509Thumbprint = Base64Url.encode(x509Thumbprint); + } + return this; + } + + /** + * The certificate identifier. + * @return The Identifier value. + */ + public CertificateIdentifier identifier() { + CertificateIdentifier identifier = null; + + if (id() != null && !id().isEmpty()) { + identifier = new CertificateIdentifier(id()); + } + + return identifier; + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java new file mode 100755 index 000000000000..61a6948046d0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java @@ -0,0 +1,99 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.List; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The certificate merge parameters. + */ +public class CertificateMergeParameters { + /** + * The certificate or the certificate chain to merge. + */ + @JsonProperty(value = "x5c", required = true) + private List x509Certificates; + + /** + * The attributes of the certificate (optional). + */ + @JsonProperty(value = "attributes") + private CertificateAttributes certificateAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the x509Certificates value. + * + * @return the x509Certificates value + */ + public List x509Certificates() { + return this.x509Certificates; + } + + /** + * Set the x509Certificates value. + * + * @param x509Certificates the x509Certificates value to set + * @return the CertificateMergeParameters object itself. + */ + public CertificateMergeParameters withX509Certificates(List x509Certificates) { + this.x509Certificates = x509Certificates; + return this; + } + + /** + * Get the certificateAttributes value. + * + * @return the certificateAttributes value + */ + public CertificateAttributes certificateAttributes() { + return this.certificateAttributes; + } + + /** + * Set the certificateAttributes value. + * + * @param certificateAttributes the certificateAttributes value to set + * @return the CertificateMergeParameters object itself. + */ + public CertificateMergeParameters withCertificateAttributes(CertificateAttributes certificateAttributes) { + this.certificateAttributes = certificateAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the CertificateMergeParameters object itself. + */ + public CertificateMergeParameters withTags(Map tags) { + this.tags = tags; + 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 new file mode 100755 index 000000000000..862d5d2ad848 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java @@ -0,0 +1,273 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.io.IOException; + +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.CertificateOperationIdentifier; + +/** + * A certificate operation is returned in case of asynchronous requests. + */ +public class CertificateOperation { + /** + * The certificate id. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * Parameters for the issuer of the X509 component of a certificate. + */ + @JsonProperty(value = "issuer") + private IssuerParameters issuerParameters; + + /** + * The certificate signing request (CSR) that is being used in the + * certificate operation. + */ + @JsonProperty(value = "csr") + private byte[] csr; + + /** + * Indicates if cancellation was requested on the certificate operation. + */ + @JsonProperty(value = "cancellation_requested") + private Boolean cancellationRequested; + + /** + * Status of the certificate operation. + */ + @JsonProperty(value = "status") + private String status; + + /** + * The status details of the certificate operation. + */ + @JsonProperty(value = "status_details") + private String statusDetails; + + /** + * Error encountered, if any, during the certificate operation. + */ + @JsonProperty(value = "error") + private Error error; + + /** + * Location which contains the result of the certificate operation. + */ + @JsonProperty(value = "target") + private String target; + + /** + * Identifier for the certificate operation. + */ + @JsonProperty(value = "request_id") + private String requestId; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get the issuerParameters value. + * + * @return the issuerParameters value + */ + public IssuerParameters issuerParameters() { + return this.issuerParameters; + } + + /** + * Set the issuerParameters value. + * + * @param issuerParameters the issuerParameters value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withIssuerParameters(IssuerParameters issuerParameters) { + this.issuerParameters = issuerParameters; + return this; + } + + /** + * Get the csr value. + * + * @return the csr value + */ + public byte[] csr() { + return this.csr; + } + + /** + * Set the csr value. + * + * @param csr the csr value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withCsr(byte[] csr) { + this.csr = csr; + return this; + } + + /** + * 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 CertificateOperation object itself. + */ + public CertificateOperation withCancellationRequested(Boolean cancellationRequested) { + this.cancellationRequested = cancellationRequested; + return this; + } + + /** + * Get the status value. + * + * @return the status value + */ + public String status() { + return this.status; + } + + /** + * Set the status value. + * + * @param status the status value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withStatus(String status) { + this.status = status; + return this; + } + + /** + * Get the statusDetails value. + * + * @return the statusDetails value + */ + public String statusDetails() { + return this.statusDetails; + } + + /** + * Set the statusDetails value. + * + * @param statusDetails the statusDetails value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withStatusDetails(String statusDetails) { + this.statusDetails = statusDetails; + return this; + } + + /** + * Get the error value. + * + * @return the error value + */ + public Error error() { + return this.error; + } + + /** + * Set the error value. + * + * @param error the error value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withError(Error error) { + this.error = error; + return this; + } + + /** + * Get the target value. + * + * @return the target value + */ + public String target() { + return this.target; + } + + /** + * Set the target value. + * + * @param target the target value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withTarget(String target) { + this.target = target; + return this; + } + + /** + * Get the requestId value. + * + * @return the requestId value + */ + public String requestId() { + return this.requestId; + } + + /** + * Set the requestId value. + * + * @param requestId the requestId value to set + * @return the CertificateOperation object itself. + */ + public CertificateOperation withRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * The certificate operation identifier. + * @return the identifier value + */ + public CertificateOperationIdentifier certificateOperationIdentifier() { + if (id() == null || id().isEmpty()) { + return null; + } + return new CertificateOperationIdentifier(id()); + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} 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 000000000000..4179f67fe606 --- /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 1.0.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/CertificatePolicy.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java new file mode 100755 index 000000000000..1f43ad5bbfa7 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java @@ -0,0 +1,192 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Management policy for a certificate. + */ +public class CertificatePolicy { + /** + * The certificate id. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * Properties of the key backing a certificate. + */ + @JsonProperty(value = "key_props") + private KeyProperties keyProperties; + + /** + * Properties of the secret backing a certificate. + */ + @JsonProperty(value = "secret_props") + private SecretProperties secretProperties; + + /** + * Properties of the X509 component of a certificate. + */ + @JsonProperty(value = "x509_props") + private X509CertificateProperties x509CertificateProperties; + + /** + * Actions that will be performed by Key Vault over the lifetime of a + * certificate. + */ + @JsonProperty(value = "lifetime_actions") + private List lifetimeActions; + + /** + * Parameters for the issuer of the X509 component of a certificate. + */ + @JsonProperty(value = "issuer") + private IssuerParameters issuerParameters; + + /** + * The certificate attributes. + */ + @JsonProperty(value = "attributes") + private CertificateAttributes attributes; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get the keyProperties value. + * + * @return the keyProperties value + */ + public KeyProperties keyProperties() { + return this.keyProperties; + } + + /** + * Set the keyProperties value. + * + * @param keyProperties the keyProperties value to set + * @return the CertificatePolicy object itself. + */ + public CertificatePolicy withKeyProperties(KeyProperties keyProperties) { + this.keyProperties = keyProperties; + return this; + } + + /** + * Get the secretProperties value. + * + * @return the secretProperties value + */ + public SecretProperties secretProperties() { + return this.secretProperties; + } + + /** + * Set the secretProperties value. + * + * @param secretProperties the secretProperties value to set + * @return the CertificatePolicy object itself. + */ + public CertificatePolicy withSecretProperties(SecretProperties secretProperties) { + this.secretProperties = secretProperties; + return this; + } + + /** + * Get the x509CertificateProperties value. + * + * @return the x509CertificateProperties value + */ + public X509CertificateProperties x509CertificateProperties() { + return this.x509CertificateProperties; + } + + /** + * Set the x509CertificateProperties value. + * + * @param x509CertificateProperties the x509CertificateProperties value to set + * @return the CertificatePolicy object itself. + */ + public CertificatePolicy withX509CertificateProperties(X509CertificateProperties x509CertificateProperties) { + this.x509CertificateProperties = x509CertificateProperties; + return this; + } + + /** + * Get the lifetimeActions value. + * + * @return the lifetimeActions value + */ + public List lifetimeActions() { + return this.lifetimeActions; + } + + /** + * Set the lifetimeActions value. + * + * @param lifetimeActions the lifetimeActions value to set + * @return the CertificatePolicy object itself. + */ + public CertificatePolicy withLifetimeActions(List lifetimeActions) { + this.lifetimeActions = lifetimeActions; + return this; + } + + /** + * Get the issuerParameters value. + * + * @return the issuerParameters value + */ + public IssuerParameters issuerParameters() { + return this.issuerParameters; + } + + /** + * Set the issuerParameters value. + * + * @param issuerParameters the issuerParameters value to set + * @return the CertificatePolicy object itself. + */ + public CertificatePolicy withIssuerParameters(IssuerParameters issuerParameters) { + this.issuerParameters = issuerParameters; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public CertificateAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the CertificatePolicy object itself. + */ + public CertificatePolicy withAttributes(CertificateAttributes attributes) { + this.attributes = attributes; + 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 new file mode 100755 index 000000000000..af9bbe3f566d --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java @@ -0,0 +1,98 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 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). + */ + @JsonProperty(value = "attributes") + private CertificateAttributes certificateAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + 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. + * + * @return the certificateAttributes value + */ + public CertificateAttributes certificateAttributes() { + return this.certificateAttributes; + } + + /** + * Set the certificateAttributes value. + * + * @param certificateAttributes the certificateAttributes value to set + * @return the CertificateUpdateParameters object itself. + */ + public CertificateUpdateParameters withCertificateAttributes(CertificateAttributes certificateAttributes) { + this.certificateAttributes = certificateAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the CertificateUpdateParameters object itself. + */ + public CertificateUpdateParameters withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java new file mode 100755 index 000000000000..dd7111eb6f2d --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java @@ -0,0 +1,97 @@ +/** + * 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 1.0.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 contact information for the vault certificates. + */ +public class Contact { + /** + * Email addresss. + */ + @JsonProperty(value = "email") + private String emailAddress; + + /** + * Name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Phone number. + */ + @JsonProperty(value = "phone") + private String phone; + + /** + * Get the emailAddress value. + * + * @return the emailAddress value + */ + public String emailAddress() { + return this.emailAddress; + } + + /** + * Set the emailAddress value. + * + * @param emailAddress the emailAddress value to set + * @return the Contact object itself. + */ + public Contact withEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + return this; + } + + /** + * Get the name value. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name value. + * + * @param name the name value to set + * @return the Contact object itself. + */ + public Contact withName(String name) { + this.name = name; + return this; + } + + /** + * Get the phone value. + * + * @return the phone value + */ + public String phone() { + return this.phone; + } + + /** + * Set the phone value. + * + * @param phone the phone value to set + * @return the Contact object itself. + */ + public Contact withPhone(String phone) { + this.phone = phone; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java new file mode 100755 index 000000000000..166f0392f293 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java @@ -0,0 +1,61 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The contacts for the vault certificates. + */ +public class Contacts { + /** + * Identifier for the contacts collection. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * The contact list for the vault certificates. + */ + @JsonProperty(value = "contacts") + private List contactList; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get the contactList value. + * + * @return the contactList value + */ + public List contactList() { + return this.contactList; + } + + /** + * Set the contactList value. + * + * @param contactList the contactList value to set + * @return the Contacts object itself. + */ + public Contacts withContactList(List contactList) { + this.contactList = contactList; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java new file mode 100755 index 000000000000..103ad6182c75 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java @@ -0,0 +1,64 @@ +/** + * 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 1.0.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 key vault server error. + */ +public class Error { + /** + * The error code. + */ + @JsonProperty(value = "code", access = JsonProperty.Access.WRITE_ONLY) + private String code; + + /** + * The error message. + */ + @JsonProperty(value = "message", access = JsonProperty.Access.WRITE_ONLY) + private String message; + + /** + * The innerError property. + */ + @JsonProperty(value = "innererror", access = JsonProperty.Access.WRITE_ONLY) + private Error innerError; + + /** + * Get the code value. + * + * @return the code value + */ + public String code() { + return this.code; + } + + /** + * Get the message value. + * + * @return the message value + */ + public String message() { + return this.message; + } + + /** + * Get the innerError value. + * + * @return the innerError value + */ + public Error innerError() { + return this.innerError; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java new file mode 100755 index 000000000000..7c1b9c47b271 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java @@ -0,0 +1,83 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The attributes of an issuer managed by the Key Vault service. + */ +public class IssuerAttributes { + /** + * Determines whether the issuer is enabled. + */ + @JsonProperty(value = "enabled") + private Boolean enabled; + + /** + * Creation time in UTC. + */ + @JsonProperty(value = "created", access = JsonProperty.Access.WRITE_ONLY) + private Long created; + + /** + * Last updated time in UTC. + */ + @JsonProperty(value = "updated", access = JsonProperty.Access.WRITE_ONLY) + private Long updated; + + /** + * Get the enabled value. + * + * @return the enabled value + */ + public Boolean enabled() { + return this.enabled; + } + + /** + * Set the enabled value. + * + * @param enabled the enabled value to set + * @return the IssuerAttributes object itself. + */ + public IssuerAttributes withEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Get the created value. + * + * @return the created value + */ + public DateTime created() { + if (this.created == null) { + return null; + } + return new DateTime(this.created * 1000L, DateTimeZone.UTC); + } + + /** + * Get the updated value. + * + * @return the updated value + */ + public DateTime updated() { + if (this.updated == null) { + return null; + } + return new DateTime(this.updated * 1000L, DateTimeZone.UTC); + } + +} 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 new file mode 100755 index 000000000000..89d8500663b0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java @@ -0,0 +1,168 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.io.IOException; + +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.IssuerIdentifier; + +/** + * The issuer for Key Vault certificate. + */ +public class IssuerBundle { + /** + * Identifier for the issuer object. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * The issuer provider. + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * The credentials to be used for the issuer. + */ + @JsonProperty(value = "credentials") + private IssuerCredentials credentials; + + /** + * Details of the organization as provided to the issuer. + */ + @JsonProperty(value = "org_details") + private OrganizationDetails organizationDetails; + + /** + * Attributes of the issuer object. + */ + @JsonProperty(value = "attributes") + private IssuerAttributes attributes; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * 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 IssuerBundle object itself. + */ + public IssuerBundle 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 IssuerBundle object itself. + */ + public IssuerBundle 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 IssuerBundle object itself. + */ + public IssuerBundle 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 IssuerBundle object itself. + */ + public IssuerBundle withAttributes(IssuerAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * The issuer identifier. + * @return identifier for issuer + */ + public IssuerIdentifier issuerIdentifier() { + if (id() == null || id().isEmpty()) { + return null; + } + return new IssuerIdentifier(id()); + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java new file mode 100755 index 000000000000..165d1e1534f6 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java @@ -0,0 +1,71 @@ +/** + * 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 1.0.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 credentials to be used for the certificate issuer. + */ +public class IssuerCredentials { + /** + * The user name/account name/account id. + */ + @JsonProperty(value = "account_id") + private String accountId; + + /** + * The password/secret/account key. + */ + @JsonProperty(value = "pwd") + private String password; + + /** + * Get the accountId value. + * + * @return the accountId value + */ + public String accountId() { + return this.accountId; + } + + /** + * Set the accountId value. + * + * @param accountId the accountId value to set + * @return the IssuerCredentials object itself. + */ + public IssuerCredentials withAccountId(String accountId) { + this.accountId = accountId; + return this; + } + + /** + * Get the password value. + * + * @return the password value + */ + public String password() { + return this.password; + } + + /** + * Set the password value. + * + * @param password the password value to set + * @return the IssuerCredentials object itself. + */ + public IssuerCredentials withPassword(String password) { + this.password = password; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java new file mode 100644 index 000000000000..fe8f6a857c07 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java @@ -0,0 +1,72 @@ +/** + * 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 1.0.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; + +/** + * Parameters for the issuer of the X509 component of a certificate. + */ +public class IssuerParameters { + /** + * Name of the referenced issuer object or reserved names; for example, + * 'Self' or 'Unknown'. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Type of certificate to be requested from the issuer provider. + */ + @JsonProperty(value = "cty") + private String certificateType; + + /** + * Get the name value. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name value. + * + * @param name the name value to set + * @return the IssuerParameters object itself. + */ + public IssuerParameters withName(String name) { + this.name = name; + return this; + } + + /** + * Get the certificateType value. + * + * @return the certificateType value + */ + public String certificateType() { + return this.certificateType; + } + + /** + * Set the certificateType value. + * + * @param certificateType the certificateType value to set + * @return the IssuerParameters object itself. + */ + public IssuerParameters withCertificateType(String certificateType) { + this.certificateType = certificateType; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java new file mode 100755 index 000000000000..59910d461f84 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java @@ -0,0 +1,18 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + + +/** + * The attributes of a key managed by the key vault service. + */ +public class KeyAttributes extends Attributes { +} 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 new file mode 100755 index 000000000000..cfe5f0399e88 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java @@ -0,0 +1,144 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.io.IOException; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonGenerationException; +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.fasterxml.jackson.annotation.JsonProperty; + +/** + * A KeyBundle consisting of a WebKey plus its attributes. + */ +public class KeyBundle { + /** + * The Json web key. + */ + @JsonProperty(value = "key") + private JsonWebKey key; + + /** + * The key management attributes. + */ + @JsonProperty(value = "attributes") + private KeyAttributes attributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * True if the key's lifetime is managed by key vault. If this is a key + * backing a certificate, then managed will be true. + */ + @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) + private Boolean managed; + + /** + * Get the key value. + * + * @return the key value + */ + public JsonWebKey key() { + return this.key; + } + + /** + * Set the key value. + * + * @param key the key value to set + * @return the KeyBundle object itself. + */ + public KeyBundle withKey(JsonWebKey key) { + this.key = key; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public KeyAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the KeyBundle object itself. + */ + public KeyBundle withAttributes(KeyAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the KeyBundle object itself. + */ + public KeyBundle withTags(Map tags) { + this.tags = 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 + */ + public KeyIdentifier keyIdentifier() { + if (key() == null || key().kid() == null || key().kid().length() == 0) { + return null; + } + return new KeyIdentifier(key().kid()); + } + + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} 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 new file mode 100755 index 000000000000..bb4e6c187a50 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java @@ -0,0 +1,155 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +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. + */ +public class KeyCreateParameters { + /** + * The type of key to create. For valid key types, see JsonWebKeyType. + * Supported JsonWebKey key types (kty) for Elliptic Curve, RSA, HSM, + * Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct'. + */ + @JsonProperty(value = "kty", required = true) + private JsonWebKeyType kty; + + /** + * The key size in bytes. For example, 1024 or 2048. + */ + @JsonProperty(value = "key_size") + private Integer keySize; + + /** + * The keyOps property. + */ + @JsonProperty(value = "key_ops") + private List keyOps; + + /** + * The keyAttributes property. + */ + @JsonProperty(value = "attributes") + private KeyAttributes keyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the kty value. + * + * @return the kty value + */ + public JsonWebKeyType kty() { + return this.kty; + } + + /** + * Set the kty value. + * + * @param kty the kty value to set + * @return the KeyCreateParameters object itself. + */ + public KeyCreateParameters withKty(JsonWebKeyType kty) { + this.kty = kty; + return this; + } + + /** + * Get the keySize value. + * + * @return the keySize value + */ + public Integer keySize() { + return this.keySize; + } + + /** + * Set the keySize value. + * + * @param keySize the keySize value to set + * @return the KeyCreateParameters object itself. + */ + public KeyCreateParameters withKeySize(Integer keySize) { + this.keySize = keySize; + return this; + } + + /** + * Get the keyOps value. + * + * @return the keyOps value + */ + public List keyOps() { + return this.keyOps; + } + + /** + * Set the keyOps value. + * + * @param keyOps the keyOps value to set + * @return the KeyCreateParameters object itself. + */ + public KeyCreateParameters withKeyOps(List keyOps) { + this.keyOps = keyOps; + return this; + } + + /** + * Get the keyAttributes value. + * + * @return the keyAttributes value + */ + public KeyAttributes keyAttributes() { + return this.keyAttributes; + } + + /** + * Set the keyAttributes value. + * + * @param keyAttributes the keyAttributes value to set + * @return the KeyCreateParameters object itself. + */ + public KeyCreateParameters withKeyAttributes(KeyAttributes keyAttributes) { + this.keyAttributes = keyAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the KeyCreateParameters object itself. + */ + public KeyCreateParameters withTags(Map tags) { + this.tags = tags; + 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 new file mode 100755 index 000000000000..7c3ec66c0186 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java @@ -0,0 +1,125 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; + +/** + * The key import parameters. + */ +public class KeyImportParameters { + /** + * Whether to import as a hardware key (HSM) or software key. + */ + @JsonProperty(value = "Hsm") + private Boolean hsm; + + /** + * The Json web key. + */ + @JsonProperty(value = "key", required = true) + private JsonWebKey key; + + /** + * The key management attributes. + */ + @JsonProperty(value = "attributes") + private KeyAttributes keyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the hsm value. + * + * @return the hsm value + */ + public Boolean hsm() { + return this.hsm; + } + + /** + * Set the hsm value. + * + * @param hsm the hsm value to set + * @return the KeyImportParameters object itself. + */ + public KeyImportParameters withHsm(Boolean hsm) { + this.hsm = hsm; + return this; + } + + /** + * Get the key value. + * + * @return the key value + */ + public JsonWebKey key() { + return this.key; + } + + /** + * Set the key value. + * + * @param key the key value to set + * @return the KeyImportParameters object itself. + */ + public KeyImportParameters withKey(JsonWebKey key) { + this.key = key; + return this; + } + + /** + * Get the keyAttributes value. + * + * @return the keyAttributes value + */ + public KeyAttributes keyAttributes() { + return this.keyAttributes; + } + + /** + * Set the keyAttributes value. + * + * @param keyAttributes the keyAttributes value to set + * @return the KeyImportParameters object itself. + */ + public KeyImportParameters withKeyAttributes(KeyAttributes keyAttributes) { + this.keyAttributes = keyAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the KeyImportParameters object itself. + */ + public KeyImportParameters withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java new file mode 100755 index 000000000000..8e0fc7d37f6b --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java @@ -0,0 +1,128 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.microsoft.azure.keyvault.KeyIdentifier; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The key item containing key metadata. + */ +public class KeyItem { + /** + * Key identifier. + */ + @JsonProperty(value = "kid") + private String kid; + + /** + * The key management attributes. + */ + @JsonProperty(value = "attributes") + private KeyAttributes attributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * True if the key's lifetime is managed by key vault. If this is a key + * backing a certificate, then managed will be true. + */ + @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) + private Boolean managed; + + /** + * Get the kid value. + * + * @return the kid value + */ + public String kid() { + return this.kid; + } + + /** + * Set the kid value. + * + * @param kid the kid value to set + * @return the KeyItem object itself. + */ + public KeyItem withKid(String kid) { + this.kid = kid; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public KeyAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the KeyItem object itself. + */ + public KeyItem withAttributes(KeyAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the KeyItem object itself. + */ + public KeyItem withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * The key identifier. + * @return The Identifier value + */ + public KeyIdentifier identifier() { + KeyIdentifier identifier = null; + + if (kid() != null && !kid().isEmpty()) { + identifier = new KeyIdentifier(kid()); + } + + return identifier; + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java new file mode 100755 index 000000000000..9c935bb5414c --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java @@ -0,0 +1,53 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The key operation result. + */ +public class KeyOperationResult { + /** + * Key identifier. + */ + @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) + private String kid; + + /** + * The result property. + */ + @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY) + private Base64Url result; + + /** + * Get the kid value. + * + * @return the kid value + */ + public String kid() { + return this.kid; + } + + /** + * Get the result value. + * + * @return the result value + */ + public byte[] result() { + if (this.result == null) { + return null; + } + return this.result.decodedBytes(); + } + +} 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 new file mode 100755 index 000000000000..5a893ce790e0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java @@ -0,0 +1,80 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.azure.keyvault.webkey.JsonWebKeyEncryptionAlgorithm; +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The key operations parameters. + */ +public class KeyOperationsParameters { + /** + * algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'. + */ + @JsonProperty(value = "alg", required = true) + private JsonWebKeyEncryptionAlgorithm algorithm; + + /** + * The value property. + */ + @JsonProperty(value = "value", required = true) + private Base64Url value; + + /** + * Get the algorithm value. + * + * @return the algorithm value + */ + public JsonWebKeyEncryptionAlgorithm algorithm() { + return this.algorithm; + } + + /** + * Set the algorithm value. + * + * @param algorithm the algorithm value to set + * @return the KeyOperationsParameters object itself. + */ + public KeyOperationsParameters withAlgorithm(JsonWebKeyEncryptionAlgorithm algorithm) { + this.algorithm = algorithm; + return this; + } + + /** + * Get the value value. + * + * @return the value value + */ + public byte[] value() { + if (this.value == null) { + return null; + } + return this.value.decodedBytes(); + } + + /** + * Set the value value. + * + * @param value the value value to set + * @return the KeyOperationsParameters object itself. + */ + public KeyOperationsParameters withValue(byte[] value) { + if (value == null) { + this.value = null; + } else { + this.value = Base64Url.encode(value); + } + 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 new file mode 100755 index 000000000000..61f339b62ba8 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java @@ -0,0 +1,123 @@ +/** + * 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 1.0.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; + +/** + * Properties of the key pair backing a certificate. + */ +public class KeyProperties { + /** + * Indicates if the private key can be exported. + */ + @JsonProperty(value = "exportable") + private Boolean exportable; + + /** + * The key type. + */ + @JsonProperty(value = "kty") + private String keyType; + + /** + * The key size in bytes. For example; 1024 or 2048. + */ + @JsonProperty(value = "key_size") + private Integer keySize; + + /** + * Indicates if the same key pair will be used on certificate renewal. + */ + @JsonProperty(value = "reuse_key") + private Boolean reuseKey; + + /** + * Get the exportable value. + * + * @return the exportable value + */ + public Boolean exportable() { + return this.exportable; + } + + /** + * Set the exportable value. + * + * @param exportable the exportable value to set + * @return the KeyProperties object itself. + */ + public KeyProperties withExportable(Boolean exportable) { + this.exportable = exportable; + return this; + } + + /** + * Get the keyType value. + * + * @return the keyType value + */ + public String keyType() { + return this.keyType; + } + + /** + * Set the keyType value. + * + * @param keyType the keyType value to set + * @return the KeyProperties object itself. + */ + public KeyProperties withKeyType(String keyType) { + this.keyType = keyType; + return this; + } + + /** + * Get the keySize value. + * + * @return the keySize value + */ + public Integer keySize() { + return this.keySize; + } + + /** + * Set the keySize value. + * + * @param keySize the keySize value to set + * @return the KeyProperties object itself. + */ + public KeyProperties withKeySize(Integer keySize) { + this.keySize = keySize; + return this; + } + + /** + * Get the reuseKey value. + * + * @return the reuseKey value + */ + public Boolean reuseKey() { + return this.reuseKey; + } + + /** + * Set the reuseKey value. + * + * @param reuseKey the reuseKey value to set + * @return the KeyProperties object itself. + */ + public KeyProperties withReuseKey(Boolean reuseKey) { + this.reuseKey = reuseKey; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java new file mode 100755 index 000000000000..3ecc2181ae2b --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java @@ -0,0 +1,53 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The key restore parameters. + */ +public class KeyRestoreParameters { + /** + * The backup blob associated with a key bundle. + */ + @JsonProperty(value = "value", required = true) + private Base64Url keyBundleBackup; + + /** + * Get the keyBundleBackup value. + * + * @return the keyBundleBackup value + */ + public byte[] keyBundleBackup() { + if (this.keyBundleBackup == null) { + return null; + } + return this.keyBundleBackup.decodedBytes(); + } + + /** + * Set the keyBundleBackup value. + * + * @param keyBundleBackup the keyBundleBackup value to set + * @return the KeyRestoreParameters object itself. + */ + public KeyRestoreParameters withKeyBundleBackup(byte[] keyBundleBackup) { + if (keyBundleBackup == null) { + this.keyBundleBackup = null; + } else { + this.keyBundleBackup = Base64Url.encode(keyBundleBackup); + } + return this; + } + +} 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 new file mode 100755 index 000000000000..50e87a32383b --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java @@ -0,0 +1,82 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The key operations parameters. + */ +public class KeySignParameters { + /** + * The signing/verification algorithm identifier. For more information on + * possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible + * values include: 'RS256', 'RS384', 'RS512', 'RSNULL'. + */ + @JsonProperty(value = "alg", required = true) + private JsonWebKeySignatureAlgorithm algorithm; + + /** + * The value property. + */ + @JsonProperty(value = "value", required = true) + private Base64Url value; + + /** + * Get the algorithm value. + * + * @return the algorithm value + */ + public JsonWebKeySignatureAlgorithm algorithm() { + return this.algorithm; + } + + /** + * Set the algorithm value. + * + * @param algorithm the algorithm value to set + * @return the KeySignParameters object itself. + */ + public KeySignParameters withAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { + this.algorithm = algorithm; + return this; + } + + /** + * Get the value value. + * + * @return the value value + */ + public byte[] value() { + if (this.value == null) { + return null; + } + return this.value.decodedBytes(); + } + + /** + * Set the value value. + * + * @param value the value value to set + * @return the KeySignParameters object itself. + */ + public KeySignParameters withValue(byte[] value) { + if (value == null) { + this.value = null; + } else { + this.value = Base64Url.encode(value); + } + 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 new file mode 100755 index 000000000000..4cdd6afd1f89 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java @@ -0,0 +1,101 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +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. + */ +public class KeyUpdateParameters { + /** + * Json web key operations. For more information on possible key + * operations, see JsonWebKeyOperation. + */ + @JsonProperty(value = "key_ops") + private List keyOps; + + /** + * The keyAttributes property. + */ + @JsonProperty(value = "attributes") + private KeyAttributes keyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the keyOps value. + * + * @return the keyOps value + */ + public List keyOps() { + return this.keyOps; + } + + /** + * Set the keyOps value. + * + * @param keyOps the keyOps value to set + * @return the KeyUpdateParameters object itself. + */ + public KeyUpdateParameters withKeyOps(List keyOps) { + this.keyOps = keyOps; + return this; + } + + /** + * Get the keyAttributes value. + * + * @return the keyAttributes value + */ + public KeyAttributes keyAttributes() { + return this.keyAttributes; + } + + /** + * Set the keyAttributes value. + * + * @param keyAttributes the keyAttributes value to set + * @return the KeyUpdateParameters object itself. + */ + public KeyUpdateParameters withKeyAttributes(KeyAttributes keyAttributes) { + this.keyAttributes = keyAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the KeyUpdateParameters object itself. + */ + public KeyUpdateParameters withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java new file mode 100755 index 000000000000..bce9c9609dd0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java @@ -0,0 +1,82 @@ +/** + * 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 1.0.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.JsonValue; + +/** + * Defines values for KeyUsageType. + */ +public final class KeyUsageType { + /** Static value digitalSignature for KeyUsageType. */ + public static final KeyUsageType DIGITAL_SIGNATURE = new KeyUsageType("digitalSignature"); + + /** Static value nonRepudiation for KeyUsageType. */ + public static final KeyUsageType NON_REPUDIATION = new KeyUsageType("nonRepudiation"); + + /** Static value keyEncipherment for KeyUsageType. */ + public static final KeyUsageType KEY_ENCIPHERMENT = new KeyUsageType("keyEncipherment"); + + /** Static value dataEncipherment for KeyUsageType. */ + public static final KeyUsageType DATA_ENCIPHERMENT = new KeyUsageType("dataEncipherment"); + + /** Static value keyAgreement for KeyUsageType. */ + public static final KeyUsageType KEY_AGREEMENT = new KeyUsageType("keyAgreement"); + + /** Static value keyCertSign for KeyUsageType. */ + public static final KeyUsageType KEY_CERT_SIGN = new KeyUsageType("keyCertSign"); + + /** Static value cRLSign for KeyUsageType. */ + public static final KeyUsageType C_RLSIGN = new KeyUsageType("cRLSign"); + + /** Static value encipherOnly for KeyUsageType. */ + public static final KeyUsageType ENCIPHER_ONLY = new KeyUsageType("encipherOnly"); + + /** Static value decipherOnly for KeyUsageType. */ + public static final KeyUsageType DECIPHER_ONLY = new KeyUsageType("decipherOnly"); + + private String value; + + /** + * Creates a custom value for KeyUsageType. + * @param value the custom value + */ + public KeyUsageType(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 KeyUsageType)) { + return false; + } + if (obj == this) { + return true; + } + KeyUsageType rhs = (KeyUsageType) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java new file mode 100755 index 000000000000..4d36aeafe0e0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.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. + * + * Code generated by Microsoft (R) AutoRest Code Generator 1.0.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 key vault error exception. + */ +public class KeyVaultError { + /** + * The error property. + */ + @JsonProperty(value = "error", access = JsonProperty.Access.WRITE_ONLY) + private Error error; + + /** + * Get the error value. + * + * @return the error value + */ + public Error error() { + return this.error; + } + +} 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 new file mode 100755 index 000000000000..1fa9ca334401 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java @@ -0,0 +1,46 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.rest.RestException; +import okhttp3.ResponseBody; +import retrofit2.Response; + +/** + * Exception thrown for an invalid response with KeyVaultError information. + */ +public class KeyVaultErrorException extends RestException { + /** + * Initializes a new instance of the KeyVaultErrorException class. + * + * @param message the exception message or the response content if a message is not available + * @param response the HTTP response + */ + public KeyVaultErrorException(final String message, final Response response) { + super(message, response); + } + + /** + * Initializes a new instance of the KeyVaultErrorException class. + * + * @param message the exception message or the response content if a message is not available + * @param response the HTTP response + * @param body the deserialized response body + */ + public KeyVaultErrorException(final String message, final Response response, final KeyVaultError body) { + super(message, response, body); + } + + @Override + public KeyVaultError body() { + return (KeyVaultError) super.body(); + } +} 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 new file mode 100755 index 000000000000..5c0d50d96820 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java @@ -0,0 +1,115 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm; +import com.microsoft.rest.Base64Url; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The key verify parameters. + */ +public class KeyVerifyParameters { + /** + * The signing/verification algorithm. For more information on possible + * algorithm types, see JsonWebKeySignatureAlgorithm. Possible values + * include: 'RS256', 'RS384', 'RS512', 'RSNULL'. + */ + @JsonProperty(value = "alg", required = true) + private JsonWebKeySignatureAlgorithm algorithm; + + /** + * The digest used for signing. + */ + @JsonProperty(value = "digest", required = true) + private Base64Url digest; + + /** + * The signature to be verified. + */ + @JsonProperty(value = "value", required = true) + private Base64Url signature; + + /** + * Get the algorithm value. + * + * @return the algorithm value + */ + public JsonWebKeySignatureAlgorithm algorithm() { + return this.algorithm; + } + + /** + * Set the algorithm value. + * + * @param algorithm the algorithm value to set + * @return the KeyVerifyParameters object itself. + */ + public KeyVerifyParameters withAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { + this.algorithm = algorithm; + return this; + } + + /** + * Get the digest value. + * + * @return the digest value + */ + public byte[] digest() { + if (this.digest == null) { + return null; + } + return this.digest.decodedBytes(); + } + + /** + * Set the digest value. + * + * @param digest the digest value to set + * @return the KeyVerifyParameters object itself. + */ + public KeyVerifyParameters withDigest(byte[] digest) { + if (digest == null) { + this.digest = null; + } else { + this.digest = Base64Url.encode(digest); + } + return this; + } + + /** + * Get the signature value. + * + * @return the signature value + */ + public byte[] signature() { + if (this.signature == null) { + return null; + } + return this.signature.decodedBytes(); + } + + /** + * Set the signature value. + * + * @param signature the signature value to set + * @return the KeyVerifyParameters object itself. + */ + public KeyVerifyParameters withSignature(byte[] signature) { + if (signature == null) { + this.signature = null; + } else { + this.signature = Base64Url.encode(signature); + } + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java new file mode 100755 index 000000000000..bd62f37bfb67 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.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. + * + * Code generated by Microsoft (R) AutoRest Code Generator 1.0.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 key verify result. + */ +public class KeyVerifyResult { + /** + * True if the signature is verified, otherwise false. + */ + @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY) + private Boolean value; + + /** + * Get the value value. + * + * @return the value value + */ + public Boolean value() { + return this.value; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java new file mode 100755 index 000000000000..8af57a3fc927 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java @@ -0,0 +1,72 @@ +/** + * 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 1.0.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; + +/** + * Action and its trigger that will be performed by Key Vault over the lifetime + * of a certificate. + */ +public class LifetimeAction { + /** + * The condition that will execute the action. + */ + @JsonProperty(value = "trigger") + private Trigger trigger; + + /** + * The action that will be executed. + */ + @JsonProperty(value = "action") + private Action action; + + /** + * Get the trigger value. + * + * @return the trigger value + */ + public Trigger trigger() { + return this.trigger; + } + + /** + * Set the trigger value. + * + * @param trigger the trigger value to set + * @return the LifetimeAction object itself. + */ + public LifetimeAction withTrigger(Trigger trigger) { + this.trigger = trigger; + return this; + } + + /** + * Get the action value. + * + * @return the action value + */ + public Action action() { + return this.action; + } + + /** + * Set the action value. + * + * @param action the action value to set + * @return the LifetimeAction object itself. + */ + public LifetimeAction withAction(Action action) { + this.action = action; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java new file mode 100755 index 000000000000..14c49454359b --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java @@ -0,0 +1,72 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Details of the organization of the certificate issuer. + */ +public class OrganizationDetails { + /** + * Id of the organization. + */ + @JsonProperty(value = "id") + private String id; + + /** + * Details of the organization administrator. + */ + @JsonProperty(value = "admin_details") + private List adminDetails; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the id value. + * + * @param id the id value to set + * @return the OrganizationDetails object itself. + */ + public OrganizationDetails withId(String id) { + this.id = id; + return this; + } + + /** + * Get the adminDetails value. + * + * @return the adminDetails value + */ + public List adminDetails() { + return this.adminDetails; + } + + /** + * Set the adminDetails value. + * + * @param adminDetails the adminDetails value to set + * @return the OrganizationDetails object itself. + */ + public OrganizationDetails withAdminDetails(List adminDetails) { + this.adminDetails = adminDetails; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java new file mode 100755 index 000000000000..ebfecbb4e6fa --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java @@ -0,0 +1,77 @@ +/** + * 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 1.0.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; +import com.microsoft.azure.Page; +import java.util.List; + +/** + * An instance of this class defines a page of Azure resources and a link to + * get the next page of resources, if any. + * + * @param type of Azure resource + */ +public class PageImpl implements Page { + /** + * The link to the next page. + */ + @JsonProperty("nextLink") + private String nextPageLink; + + /** + * The list of items. + */ + @JsonProperty("value") + private List items; + + /** + * Gets the link to the next page. + * + * @return the link to the next page. + */ + @Override + public String nextPageLink() { + return this.nextPageLink; + } + + /** + * Gets the list of items. + * + * @return the list of items in {@link List}. + */ + @Override + public List items() { + return items; + } + + /** + * Sets the link to the next page. + * + * @param nextPageLink the link to the next page. + * @return this Page object itself. + */ + public PageImpl setNextPageLink(String nextPageLink) { + this.nextPageLink = nextPageLink; + return this; + } + + /** + * Sets the list of items. + * + * @param items the list of items in {@link List}. + * @return this Page object itself. + */ + public PageImpl setItems(List items) { + this.items = items; + return this; + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java new file mode 100755 index 000000000000..9067674bcda9 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.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. + * + * Code generated by Microsoft (R) AutoRest Code Generator 1.0.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 pending certificate signing request result. + */ +public class PendingCertificateSigningRequestResult { + /** + * The pending certificate signing request as Base64 encoded string. + */ + @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY) + private String value; + + /** + * Get the value value. + * + * @return the value value + */ + public String value() { + return this.value; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java new file mode 100755 index 000000000000..59b8463d65f5 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java @@ -0,0 +1,18 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + + +/** + * The secret management attributes. + */ +public class SecretAttributes extends Attributes { +} 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 new file mode 100755 index 000000000000..0743b08e0182 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java @@ -0,0 +1,213 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +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; + +/** + * A secret consisting of a value, id and its attributes. + */ +public class SecretBundle { + /** + * The secret value. + */ + @JsonProperty(value = "value") + private String value; + + /** + * The secret id. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The content type of the secret. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /** + * The secret management attributes. + */ + @JsonProperty(value = "attributes") + private SecretAttributes attributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * If this is a secret backing a KV certificate, then this field specifies + * the corresponding key backing the KV certificate. + */ + @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) + private String kid; + + /** + * True if the secret's lifetime is managed by key vault. If this is a + * secret backing a certificate, then managed will be true. + */ + @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) + private Boolean managed; + + /** + * Get the value value. + * + * @return the value value + */ + public String value() { + return this.value; + } + + /** + * Set the value value. + * + * @param value the value value to set + * @return the SecretBundle object itself. + */ + public SecretBundle withValue(String value) { + this.value = value; + return this; + } + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the id value. + * + * @param id the id value to set + * @return the SecretBundle object itself. + */ + public SecretBundle withId(String id) { + this.id = id; + return this; + } + + /** + * Get the contentType value. + * + * @return the contentType value + */ + public String contentType() { + return this.contentType; + } + + /** + * Set the contentType value. + * + * @param contentType the contentType value to set + * @return the SecretBundle object itself. + */ + public SecretBundle withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public SecretAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the SecretBundle object itself. + */ + public SecretBundle withAttributes(SecretAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the SecretBundle object itself. + */ + public SecretBundle withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the kid value. + * + * @return the kid value + */ + public String kid() { + return this.kid; + } + + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * the secret identifier. + * @return The Identifier value + */ + public SecretIdentifier secretIdentifier() { + if (id() == null || id().length() == 0) { + return null; + } + return new SecretIdentifier(id()); + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonGenerationException e) { + throw new IllegalStateException(e); + } catch (JsonMappingException e) { + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + +} 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 new file mode 100755 index 000000000000..f73fd1dbefe0 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java @@ -0,0 +1,154 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.microsoft.azure.keyvault.SecretIdentifier; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The secret item containing secret metadata. + */ +public class SecretItem { + /** + * Secret identifier. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The secret management attributes. + */ + @JsonProperty(value = "attributes") + private SecretAttributes attributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Type of the secret value such as a password. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /** + * True if the secret's lifetime is managed by key vault. If this is a key + * backing a certificate, then managed will be true. + */ + @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) + private Boolean managed; + + /** + * Get the id value. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the id value. + * + * @param id the id value to set + * @return the SecretItem object itself. + */ + public SecretItem withId(String id) { + this.id = id; + return this; + } + + /** + * Get the attributes value. + * + * @return the attributes value + */ + public SecretAttributes attributes() { + return this.attributes; + } + + /** + * Set the attributes value. + * + * @param attributes the attributes value to set + * @return the SecretItem object itself. + */ + public SecretItem withAttributes(SecretAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the SecretItem object itself. + */ + public SecretItem withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the contentType value. + * + * @return the contentType value + */ + public String contentType() { + return this.contentType; + } + + /** + * Set the contentType value. + * + * @param contentType the contentType value to set + * @return the SecretItem object itself. + */ + public SecretItem withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the managed value. + * + * @return the managed value + */ + public Boolean managed() { + return this.managed; + } + + /** + * the secret identifier. + * @return The Identifier value + */ + public SecretIdentifier identifier() { + SecretIdentifier identifier = null; + + if (id() != null && !id().isEmpty()) { + identifier = new SecretIdentifier(id()); + } + + return identifier; + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java new file mode 100755 index 000000000000..f5b4bbc5db3d --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.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 1.0.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; + +/** + * Properties of the key backing a certificate. + */ +public class SecretProperties { + /** + * The media type (MIME type). + */ + @JsonProperty(value = "contentType") + private String contentType; + + /** + * Get the contentType value. + * + * @return the contentType value + */ + public String contentType() { + return this.contentType; + } + + /** + * Set the contentType value. + * + * @param contentType the contentType value to set + * @return the SecretProperties object itself. + */ + public SecretProperties withContentType(String contentType) { + this.contentType = contentType; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java new file mode 100755 index 000000000000..af9172c65939 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java @@ -0,0 +1,124 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The secret set parameters. + */ +public class SecretSetParameters { + /** + * The value of the secret. + */ + @JsonProperty(value = "value", required = true) + private String value; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Type of the secret value such as a password. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /** + * The secret management attributes. + */ + @JsonProperty(value = "attributes") + private SecretAttributes secretAttributes; + + /** + * Get the value value. + * + * @return the value value + */ + public String value() { + return this.value; + } + + /** + * Set the value value. + * + * @param value the value value to set + * @return the SecretSetParameters object itself. + */ + public SecretSetParameters withValue(String value) { + this.value = value; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the SecretSetParameters object itself. + */ + public SecretSetParameters withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the contentType value. + * + * @return the contentType value + */ + public String contentType() { + return this.contentType; + } + + /** + * Set the contentType value. + * + * @param contentType the contentType value to set + * @return the SecretSetParameters object itself. + */ + public SecretSetParameters withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the secretAttributes value. + * + * @return the secretAttributes value + */ + public SecretAttributes secretAttributes() { + return this.secretAttributes; + } + + /** + * Set the secretAttributes value. + * + * @param secretAttributes the secretAttributes value to set + * @return the SecretSetParameters object itself. + */ + public SecretSetParameters withSecretAttributes(SecretAttributes secretAttributes) { + this.secretAttributes = secretAttributes; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java new file mode 100755 index 000000000000..a3f831f985c6 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java @@ -0,0 +1,98 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The secret update parameters. + */ +public class SecretUpdateParameters { + /** + * Type of the secret value such as a password. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /** + * The secret management attributes. + */ + @JsonProperty(value = "attributes") + private SecretAttributes secretAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get the contentType value. + * + * @return the contentType value + */ + public String contentType() { + return this.contentType; + } + + /** + * Set the contentType value. + * + * @param contentType the contentType value to set + * @return the SecretUpdateParameters object itself. + */ + public SecretUpdateParameters withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the secretAttributes value. + * + * @return the secretAttributes value + */ + public SecretAttributes secretAttributes() { + return this.secretAttributes; + } + + /** + * Set the secretAttributes value. + * + * @param secretAttributes the secretAttributes value to set + * @return the SecretUpdateParameters object itself. + */ + public SecretUpdateParameters withSecretAttributes(SecretAttributes secretAttributes) { + this.secretAttributes = secretAttributes; + return this; + } + + /** + * Get the tags value. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags value. + * + * @param tags the tags value to set + * @return the SecretUpdateParameters object itself. + */ + public SecretUpdateParameters withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java new file mode 100755 index 000000000000..ec4787470953 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java @@ -0,0 +1,98 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The subject alternate names of a X509 object. + */ +public class SubjectAlternativeNames { + /** + * Email addresses. + */ + @JsonProperty(value = "emails") + private List emails; + + /** + * Domain names. + */ + @JsonProperty(value = "dns_names") + private List dnsNames; + + /** + * User principal names. + */ + @JsonProperty(value = "upns") + private List upns; + + /** + * Get the emails value. + * + * @return the emails value + */ + public List emails() { + return this.emails; + } + + /** + * Set the emails value. + * + * @param emails the emails value to set + * @return the SubjectAlternativeNames object itself. + */ + public SubjectAlternativeNames withEmails(List emails) { + this.emails = emails; + return this; + } + + /** + * Get the dnsNames value. + * + * @return the dnsNames value + */ + public List dnsNames() { + return this.dnsNames; + } + + /** + * Set the dnsNames value. + * + * @param dnsNames the dnsNames value to set + * @return the SubjectAlternativeNames object itself. + */ + public SubjectAlternativeNames withDnsNames(List dnsNames) { + this.dnsNames = dnsNames; + return this; + } + + /** + * Get the upns value. + * + * @return the upns value + */ + public List upns() { + return this.upns; + } + + /** + * Set the upns value. + * + * @param upns the upns value to set + * @return the SubjectAlternativeNames object itself. + */ + public SubjectAlternativeNames withUpns(List upns) { + this.upns = upns; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java new file mode 100755 index 000000000000..dc06dd4e24af --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java @@ -0,0 +1,72 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A condition to be satisfied for an action to be executed. + */ +public class Trigger { + /** + * Percentage of lifetime at which to trigger. Value should be between 1 + * and 99. + */ + @JsonProperty(value = "lifetime_percentage") + private Integer lifetimePercentage; + + /** + * Days before expiry. + */ + @JsonProperty(value = "days_before_expiry") + private Integer daysBeforeExpiry; + + /** + * Get the lifetimePercentage value. + * + * @return the lifetimePercentage value + */ + public Integer lifetimePercentage() { + return this.lifetimePercentage; + } + + /** + * Set the lifetimePercentage value. + * + * @param lifetimePercentage the lifetimePercentage value to set + * @return the Trigger object itself. + */ + public Trigger withLifetimePercentage(Integer lifetimePercentage) { + this.lifetimePercentage = lifetimePercentage; + return this; + } + + /** + * Get the daysBeforeExpiry value. + * + * @return the daysBeforeExpiry value + */ + public Integer daysBeforeExpiry() { + return this.daysBeforeExpiry; + } + + /** + * Set the daysBeforeExpiry value. + * + * @param daysBeforeExpiry the daysBeforeExpiry value to set + * @return the Trigger object itself. + */ + public Trigger withDaysBeforeExpiry(Integer daysBeforeExpiry) { + this.daysBeforeExpiry = daysBeforeExpiry; + return this; + } + +} 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 new file mode 100755 index 000000000000..59fa52ef7063 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java @@ -0,0 +1,150 @@ +/** + * 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 1.0.0.0 + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package com.microsoft.azure.keyvault.models; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Properties of the X509 component of a certificate. + */ +public class X509CertificateProperties { + /** + * The subject name. Should be a valid X509 distinguished Name. + */ + @JsonProperty(value = "subject") + private String subject; + + /** + * The enhanced key usage. + */ + @JsonProperty(value = "ekus") + private List ekus; + + /** + * The subject alternative names. + */ + @JsonProperty(value = "sans") + private SubjectAlternativeNames subjectAlternativeNames; + + /** + * List of key usages. + */ + @JsonProperty(value = "key_usage") + private List keyUsage; + + /** + * The duration that the ceritifcate is valid in months. + */ + @JsonProperty(value = "validity_months") + private Integer validityInMonths; + + /** + * Get the subject value. + * + * @return the subject value + */ + public String subject() { + return this.subject; + } + + /** + * Set the subject value. + * + * @param subject the subject value to set + * @return the X509CertificateProperties object itself. + */ + public X509CertificateProperties withSubject(String subject) { + this.subject = subject; + return this; + } + + /** + * Get the ekus value. + * + * @return the ekus value + */ + public List ekus() { + return this.ekus; + } + + /** + * Set the ekus value. + * + * @param ekus the ekus value to set + * @return the X509CertificateProperties object itself. + */ + public X509CertificateProperties withEkus(List ekus) { + this.ekus = ekus; + return this; + } + + /** + * Get the subjectAlternativeNames value. + * + * @return the subjectAlternativeNames value + */ + public SubjectAlternativeNames subjectAlternativeNames() { + return this.subjectAlternativeNames; + } + + /** + * Set the subjectAlternativeNames value. + * + * @param subjectAlternativeNames the subjectAlternativeNames value to set + * @return the X509CertificateProperties object itself. + */ + public X509CertificateProperties withSubjectAlternativeNames(SubjectAlternativeNames subjectAlternativeNames) { + this.subjectAlternativeNames = subjectAlternativeNames; + return this; + } + + /** + * Get the keyUsage value. + * + * @return the keyUsage value + */ + public List keyUsage() { + return this.keyUsage; + } + + /** + * Set the keyUsage value. + * + * @param keyUsage the keyUsage value to set + * @return the X509CertificateProperties object itself. + */ + public X509CertificateProperties withKeyUsage(List keyUsage) { + this.keyUsage = keyUsage; + return this; + } + + /** + * Get the validityInMonths value. + * + * @return the validityInMonths value + */ + public Integer validityInMonths() { + return this.validityInMonths; + } + + /** + * Set the validityInMonths value. + * + * @param validityInMonths the validityInMonths value to set + * @return the X509CertificateProperties object itself. + */ + public X509CertificateProperties withValidityInMonths(Integer validityInMonths) { + this.validityInMonths = validityInMonths; + return this; + } + +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java new file mode 100755 index 000000000000..584cd6850e6c --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java @@ -0,0 +1,13 @@ +// 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 1.0.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +/** + * This package contains the models classes for KeyVaultClient. + * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + */ +package com.microsoft.azure.keyvault.models; diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java new file mode 100755 index 000000000000..f08140f306f9 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java @@ -0,0 +1,13 @@ +// 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 1.0.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +/** + * This package contains the classes for KeyVaultClient. + * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + */ +package com.microsoft.azure.keyvault; 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 new file mode 100755 index 000000000000..6237eed6ce75 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java @@ -0,0 +1,193 @@ +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.IssuerParameters; +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 create certificate request class. + */ +public final class CreateCertificateRequest { + private final String vaultBaseUrl; + private final String certificateName; + private final CertificatePolicy certificatePolicy; + private final CertificateAttributes certificateAttributes; + private final Map tags; + + /** + * the {@link CreateCertificateRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String certificateName; + + // Optional parameters + private CertificatePolicy policy; + private CertificateAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link CreateCertificateRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param certificateName + * The name of the certificate in the given vault + */ + public Builder(String vaultBaseUrl, String certificateName) { + this.vaultBaseUrl = vaultBaseUrl; + this.certificateName = certificateName; + } + + /** + * 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. + * + * @param attributes + * The attributes of the certificate. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link CreateCertificateRequest} object. + * + * @return the {@link CreateCertificateRequest} object. + */ + public CreateCertificateRequest build() { + return new CreateCertificateRequest(this); + } + } + + private CreateCertificateRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + certificateName = builder.certificateName; + + if (builder.attributes != null) { + certificateAttributes = (CertificateAttributes) new CertificateAttributes() + .withNotBefore(builder.attributes.notBefore()).withEnabled(builder.attributes.enabled()) + .withExpires(builder.attributes.expires()); + } else { + certificateAttributes = 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.issuerParameters() != null) { + certificatePolicy + .withIssuerParameters(new IssuerParameters().withName(builder.policy.issuerParameters().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 = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the certificate name + */ + public String certificateName() { + return certificateName; + } + + /** + * @return the certificate policy + */ + public CertificatePolicy certificatePolicy() { + return certificatePolicy; + } + + /** + * @return the certificate attributes + */ + public CertificateAttributes certificateAttributes() { + return certificateAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} 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 new file mode 100755 index 000000000000..8aee1468265f --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java @@ -0,0 +1,193 @@ +package com.microsoft.azure.keyvault.requests; + +import java.util.ArrayList; +import java.util.Collections; +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. + */ +public final class CreateKeyRequest { + + private final String vaultBaseUrl; + private final String keyName; + private final JsonWebKeyType keyType; + private final Integer keySize; + private final List keyOperations; + private final KeyAttributes keyAttributes; + private final Map tags; + + /** + * The {@link CreateKeyRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String keyName; + private final JsonWebKeyType keyType; + + // Optional parameters + private Integer keySize; + private List keyOperations; + private KeyAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link CreateKeyRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net + * @param keyName + * The name of the key in the given vault + * @param keyType + * 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, JsonWebKeyType keyType) { + this.vaultBaseUrl = vaultBaseUrl; + this.keyName = keyName; + this.keyType = keyType; + } + + /** + * Set the key size value. + * + * @param size + * the size of the key. + * @return the Builder object itself. + */ + public Builder withKeySize(Integer size) { + this.keySize = size; + return this; + } + + /** + * Set the key operations value. + * + * @param keyOperations + * the key operation list. + * @return the Builder object itself. + */ + public Builder withKeyOperations(List keyOperations) { + this.keyOperations = keyOperations; + return this; + } + + /** + * Set the key attributes value. + * + * @param attributes + * the key management attributes value to set. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (KeyAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link CreateKeyRequest} object. + * + * @return the {@link CreateKeyRequest} object. + */ + public CreateKeyRequest build() { + return new CreateKeyRequest(this); + } + } + + private CreateKeyRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + keyName = builder.keyName; + keyType = builder.keyType; + keySize = builder.keySize; + + if (builder.keyOperations != null) { + keyOperations = new ArrayList(builder.keyOperations); + } else { + keyOperations = null; + } + + if (builder.attributes != null) { + keyAttributes = (KeyAttributes) new KeyAttributes().withNotBefore(builder.attributes.notBefore()) + .withEnabled(builder.attributes.enabled()).withExpires(builder.attributes.expires()); + } else { + keyAttributes = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the key name + */ + public String keyName() { + return keyName; + } + + /** + * @return the key type + */ + public JsonWebKeyType keyType() { + return keyType; + } + + /** + * @return the key size + */ + public Integer keySize() { + return keySize; + } + + /** + * @return the key operations + */ + public List keyOperations() { + return keyOperations; + } + + /** + * @return the key attributes + */ + public KeyAttributes keyAttributes() { + return keyAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} \ No newline at end of file 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 new file mode 100755 index 000000000000..715ffa5d245a --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java @@ -0,0 +1,230 @@ +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.IssuerParameters; +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 import certificate request class. + */ +public final class ImportCertificateRequest { + private final String vaultBaseUrl; + private final String certificateName; + private final String base64EncodedCertificate; + private final String password; + private final CertificatePolicy certificatePolicy; + private final CertificateAttributes certificateAttributes; + private final Map tags; + + /** + * the {@link ImportCertificateRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String certificateName; + private final String base64EncodedCertificate; + + // Optional parameters + private String password; + private CertificatePolicy policy; + private CertificateAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link ImportCertificateRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net + * @param certificateName + * The name of the certificate in the given vault + * @param base64EncodedCertificate + * Base64 encoded representation of the certificate object to + * import. This certificate needs to contain the private key. + */ + public Builder(String vaultBaseUrl, String certificateName, String base64EncodedCertificate) { + this.vaultBaseUrl = vaultBaseUrl; + this.certificateName = certificateName; + this.base64EncodedCertificate = base64EncodedCertificate; + } + + /** + * Set the password. + * + * @param password + * If the private key in base64EncodedCertificate is + * encrypted, the password used for encryption. + * @return the Builder object itself. + */ + public Builder withPassword(String password) { + this.password = password; + return this; + } + + /** + * Set the certificate policy. + * + * @param policy + * The management policy for the certificate. + * @return the Builder object itself. + */ + public Builder withPolicy(CertificatePolicy policy) { + this.policy = policy; + return this; + } + + /** + * Set the certificate attributes. + * + * @param attributes + * The attributes of the certificate. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link ImportCertificateRequest} object. + * + * @return the {@link ImportCertificateRequest} object. + */ + public ImportCertificateRequest build() { + return new ImportCertificateRequest(this); + } + } + + private ImportCertificateRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + certificateName = builder.certificateName; + base64EncodedCertificate = builder.base64EncodedCertificate; + password = builder.password; + + if (builder.attributes != null) { + certificateAttributes = (CertificateAttributes) new CertificateAttributes() + .withNotBefore(builder.attributes.notBefore()).withEnabled(builder.attributes.enabled()) + .withExpires(builder.attributes.expires()); + } + else { + certificateAttributes = 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.issuerParameters() != null) { + certificatePolicy + .withIssuerParameters(new IssuerParameters().withName(builder.policy.issuerParameters().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 = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the certificate name + */ + public String certificateName() { + return certificateName; + } + + /** + * @return the base64 encoded certificate + */ + public String base64EncodedCertificate() { + return base64EncodedCertificate; + } + + /** + * @return the password + */ + public String password() { + return password; + } + + /** + * @return the certificatePolicy + */ + public CertificatePolicy certificatePolicy() { + return certificatePolicy; + } + + /** + * @return the certificateAttributes + */ + public CertificateAttributes certificateAttributes() { + return certificateAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} 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 new file mode 100755 index 000000000000..908881d78bb9 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java @@ -0,0 +1,176 @@ +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.KeyAttributes; +import com.microsoft.azure.keyvault.webkey.JsonWebKey; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; + +/** + * The import key request class. + */ +public final class ImportKeyRequest { + + private final String vaultBaseUrl; + private final String keyName; + private final JsonWebKey key; + private final boolean isHsm; + private final KeyAttributes keyAttributes; + private final Map tags; + + /** + * The {@link ImportKeyRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String keyName; + private final JsonWebKey key; + + // Optional parameters + private boolean isHsm; + private KeyAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link ImportKeyRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param keyName + * The name of the key in the given vault. + * @param key + * The Json web key. + */ + public Builder(String vaultBaseUrl, String keyName, JsonWebKey key) { + this.vaultBaseUrl = vaultBaseUrl; + this.keyName = keyName; + this.key = key; + } + + /** + * Set the isHsm to true if the key is imported as a hardware key to + * HSM, false otherwise. + * + * @param isHsm + * True, if the key is hardware key to be stored in HSM. + * false otherwise + * @return the Builder object itself. + */ + public Builder withHsm(boolean isHsm) { + this.isHsm = isHsm; + return this; + } + + /** + * Set the key attributes value. + * + * @param attributes + * the key management attributes value to set + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (KeyAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link ImportKeyRequest} object. + * + * @return the {@link ImportKeyRequest} object. + */ + public ImportKeyRequest build() { + return new ImportKeyRequest(this); + } + } + + private ImportKeyRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + keyName = builder.keyName; + isHsm = builder.isHsm; + + if (builder.key != null) { + key = new JsonWebKey().withKty(builder.key.kty()).withN(builder.key.n()).withE(builder.key.e()) + .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())); + } + } else { + key = null; + } + + if (builder.attributes != null) { + keyAttributes = (KeyAttributes) new KeyAttributes().withNotBefore(builder.attributes.notBefore()) + .withEnabled(builder.attributes.enabled()).withExpires(builder.attributes.expires()); + } else { + keyAttributes = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the key name + */ + public String keyName() { + return keyName; + } + + /** + * @return the key + */ + public JsonWebKey key() { + return key; + } + + /** + * @return the isHsm + */ + public boolean isHsm() { + return isHsm; + } + + /** + * @return the key attribute + */ + public KeyAttributes keyAttributes() { + return keyAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } + +} 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 new file mode 100755 index 000000000000..1a1569e41d97 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java @@ -0,0 +1,139 @@ +package com.microsoft.azure.keyvault.requests; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import com.microsoft.azure.keyvault.models.Attributes; +import com.microsoft.azure.keyvault.models.CertificateAttributes; + +/** + * The merge certificate request class. + */ +public final class MergeCertificateRequest { + private final String vaultBaseUrl; + private final String certificateName; + private final List x509Certificates; + private final CertificateAttributes certificateAttributes; + private final Map tags; + + /** + * The {@link MergeCertificateRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String certificateName; + private final List x509Certificates; + + // Optional parameters + private CertificateAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link MergeCertificateRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param certificateName + * The name of the certificate in the given vault. + * @param x509Certificates + * The certificate or the certificate chain to merge. + */ + public Builder(String vaultBaseUrl, String certificateName, List x509Certificates) { + this.vaultBaseUrl = vaultBaseUrl; + this.certificateName = certificateName; + this.x509Certificates = x509Certificates; + } + + /** + * Set the attributes value. + * + * @param attributes + * The attributes of the certificate. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link MergeCertificateRequest} object. + * + * @return the {@link MergeCertificateRequest} object. + */ + public MergeCertificateRequest build() { + return new MergeCertificateRequest(this); + } + } + + private MergeCertificateRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + certificateName = builder.certificateName; + x509Certificates = new ArrayList(builder.x509Certificates); + + if (builder.attributes != null) { + certificateAttributes = (CertificateAttributes) new CertificateAttributes() + .withNotBefore(builder.attributes.notBefore()).withEnabled(builder.attributes.enabled()) + .withExpires(builder.attributes.expires()); + } else { + certificateAttributes = null; + } + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the certificate name + */ + public String certificateName() { + return certificateName; + } + + /** + * @return the x509 certificates + */ + public List x509Certificates() { + return x509Certificates; + } + + /** + * @return the certificate attributes + */ + public CertificateAttributes certificateAttributes() { + return certificateAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} 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 new file mode 100755 index 000000000000..7d582e2f5bde --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java @@ -0,0 +1,165 @@ +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.IssuerCredentials; +import com.microsoft.azure.keyvault.models.OrganizationDetails; + +/** + * The set certificate issuer request class. + */ +public final class SetCertificateIssuerRequest { + + private final String vaultBaseUrl; + private final String issuerName; + private final String provider; + private final IssuerCredentials credentials; + private final OrganizationDetails organizationDetails; + private final IssuerAttributes attributes; + + /** + * The {@link SetCertificateIssuerRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String issuerName; + private final String provider; + + // Optional parameters + private IssuerCredentials credentials; + private OrganizationDetails organizationDetails; + private IssuerAttributes attributes; + + /** + * The builder for constructing {@link SetCertificateIssuerRequest} + * object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param issuerName + * The name of the issuer. + * @param provider The name of the issuer. + */ + public Builder(String vaultBaseUrl, String issuerName, String provider) { + this.vaultBaseUrl = vaultBaseUrl; + this.issuerName = issuerName; + this.provider = provider; + } + + /** + * 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; + } + + /** + * builds the {@link SetCertificateIssuerRequest} object. + * + * @return the {@link SetCertificateIssuerRequest} object. + */ + public SetCertificateIssuerRequest build() { + return new SetCertificateIssuerRequest(this); + } + } + + private SetCertificateIssuerRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + issuerName = builder.issuerName; + 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 { + attributes = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the issuer name + */ + public String issuerName() { + return issuerName; + } + + /** + * @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 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 new file mode 100755 index 000000000000..2bfa1cc3c6bc --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java @@ -0,0 +1,160 @@ +package com.microsoft.azure.keyvault.requests; + +import java.util.Collections; +import java.util.Map; + +import com.microsoft.azure.keyvault.models.Attributes; +import com.microsoft.azure.keyvault.models.SecretAttributes; + +/** + * The set secret request class. + */ +public final class SetSecretRequest { + private final String vaultBaseUrl; + private final String secretName; + private final String value; + private final String contentType; + private final SecretAttributes secretAttributes; + private final Map tags; + + /** + * The {@link SetSecretRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String secretName; + private final String value; + + // Optional parameters + private String contentType; + private SecretAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link SetSecretRequest} object. + * + * @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 + */ + public Builder(String vaultBaseUrl, String secretName, String value) { + this.vaultBaseUrl = vaultBaseUrl; + this.secretName = secretName; + this.value = value; + } + + /** + * Set the content type value. + * + * @param contentType + * Type of the secret value such as a password + * @return the Builder object itself. + */ + public Builder withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Set the attributes value. + * + * @param attributes + * The secret management attributes. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (SecretAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link SetSecretRequest} object. + * + * @return the {@link SetSecretRequest} object. + */ + public SetSecretRequest build() { + return new SetSecretRequest(this); + } + } + + private SetSecretRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + secretName = builder.secretName; + value = builder.value; + contentType = builder.contentType; + + if (builder.attributes != null) { + secretAttributes = (SecretAttributes) new SecretAttributes().withNotBefore(builder.attributes.notBefore()) + .withEnabled(builder.attributes.enabled()).withExpires(builder.attributes.expires()); + } else { + secretAttributes = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vaultBaseUrl + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the secretName + */ + public String secretName() { + return secretName; + } + + /** + * @return the value + */ + public String value() { + return value; + } + + /** + * @return the contentType + */ + public String contentType() { + return contentType; + } + + /** + * @return the secretAttributes + */ + public SecretAttributes secretAttributes() { + return secretAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } + +} 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 new file mode 100755 index 000000000000..d743f86cabe6 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java @@ -0,0 +1,174 @@ +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.IssuerCredentials; +import com.microsoft.azure.keyvault.models.OrganizationDetails; + +/** + * The update certificate issuer request class. + */ +public final class UpdateCertificateIssuerRequest { + private final String vaultBaseUrl; + private final String issuerName; + private final String provider; + private final IssuerCredentials credentials; + private final OrganizationDetails organizationDetails; + private final IssuerAttributes attributes; + + /** + * The {@link UpdateCertificateIssuerRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String issuerName; + + // Optional parameters + private String provider; + private IssuerCredentials credentials; + private OrganizationDetails organizationDetails; + private IssuerAttributes attributes; + + /** + * The builder for constructing {@link UpdateCertificateIssuerRequest} + * object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param issuerName + * The name of the issuer in the given vault. + */ + public Builder(String vaultBaseUrl, String issuerName) { + this.vaultBaseUrl = vaultBaseUrl; + this.issuerName = issuerName; + } + + /** + * Set issuer credentials. + * + * @param provider + * The issuer provider. + * @return the Builder object itself. + */ + public Builder withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Set issuer credentials. + * + * @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; + } + + /** + * builds the {@link UpdateCertificateIssuerRequest} object. + * + * @return the {@link UpdateCertificateIssuerRequest} object. + */ + public UpdateCertificateIssuerRequest build() { + return new UpdateCertificateIssuerRequest(this); + } + } + + private UpdateCertificateIssuerRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + issuerName = builder.issuerName; + 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 { + attributes = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the issuer name + */ + public String issuerName() { + return issuerName; + } + + /** + * @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 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 new file mode 100755 index 000000000000..24f68899e111 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java @@ -0,0 +1,75 @@ +package com.microsoft.azure.keyvault.requests; + +/** + * The update certificate operation request class. + */ +public final class UpdateCertificateOperationRequest { + private final String vaultBaseUrl; + private final String certificateName; + private final Boolean cancellationRequested; + + /** + * The {@link UpdateCertificateOperationRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String certificateName; + private final Boolean cancellationRequested; + + // Optional parameters + + /** + * The builder for constructing {@link CreateCertificateRequest} object. + * + * @param vaultBaseUrl + * 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, Boolean cancellationRequested) { + this.vaultBaseUrl = vaultBaseUrl; + this.certificateName = certificateName; + this.cancellationRequested = cancellationRequested; + } + + /** + * builds the {@link UpdateCertificateOperationRequest} object. + * + * @return the {@link UpdateCertificateOperationRequest} object. + */ + public UpdateCertificateOperationRequest build() { + return new UpdateCertificateOperationRequest(this); + } + } + + private UpdateCertificateOperationRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + certificateName = builder.certificateName; + cancellationRequested = builder.cancellationRequested; + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the certificate name + */ + public String certificateName() { + return certificateName; + } + + /** + * @return the certificate policy + */ + 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 new file mode 100755 index 000000000000..eb783686250a --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java @@ -0,0 +1,133 @@ +package com.microsoft.azure.keyvault.requests; + +import java.util.ArrayList; + +import com.microsoft.azure.keyvault.models.CertificateAttributes; +import com.microsoft.azure.keyvault.models.CertificatePolicy; +import com.microsoft.azure.keyvault.models.IssuerParameters; +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 policy request class. + */ +public final class UpdateCertificatePolicyRequest { + private final String vaultBaseUrl; + private final String certificateName; + private final CertificatePolicy certificatePolicy; + + /** + * The {@link UpdateCertificatePolicyRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String certificateName; + + // Optional parameters + private CertificatePolicy policy; + + /** + * The builder for constructing {@link UpdateCertificatePolicyRequest} + * object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param certificateName + * The name of the certificate in the given vault. + */ + public Builder(String vaultBaseUrl, String certificateName) { + this.vaultBaseUrl = vaultBaseUrl; + this.certificateName = certificateName; + } + + /** + * Set the certificatePolicy value. + * + * @param certificatePolicy + * The management policy for the certificate. + * @return the Builder object itself. + */ + public Builder withPolicy(CertificatePolicy certificatePolicy) { + this.policy = certificatePolicy; + return this; + } + + /** + * builds the {@link UpdateCertificatePolicyRequest} object. + * + * @return the {@link UpdateCertificatePolicyRequest} object. + */ + public UpdateCertificatePolicyRequest build() { + return new UpdateCertificatePolicyRequest(this); + } + } + + private UpdateCertificatePolicyRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + certificateName = builder.certificateName; + + 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.issuerParameters() != null) { + certificatePolicy + .withIssuerParameters(new IssuerParameters().withName(builder.policy.issuerParameters().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(); + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the certificate name + */ + public String certificateName() { + return certificateName; + } + + /** + * @return the certificate policy + */ + public CertificatePolicy certificatePolicy() { + return 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 new file mode 100755 index 000000000000..556fecdc57e5 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java @@ -0,0 +1,215 @@ +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.IssuerParameters; +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. + */ +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; + + /** + * The {@link UpdateCertificateRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String certificateName; + + // Optional parameters + private String certificateVersion; + private CertificateAttributes attributes; + private Map tags; + private CertificatePolicy policy; + + /** + * The builder for constructing {@link UpdateCertificateRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param certificateName + * The name of the certificate in the given vault. + */ + public Builder(String vaultBaseUrl, String certificateName) { + this.vaultBaseUrl = vaultBaseUrl; + this.certificateName = certificateName; + } + + /** + * Set the certificate version value. + * + * @param version + * The version of the certificate. + * @return the Builder object itself. + */ + 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. + * + * @param attributes + * The attributes of the certificate. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (CertificateAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link UpdateCertificateRequest} object. + * + * @return the {@link UpdateCertificateRequest} object. + */ + public UpdateCertificateRequest build() { + return new UpdateCertificateRequest(this); + } + } + + private UpdateCertificateRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + certificateName = builder.certificateName; + certificateVersion = builder.certificateVersion == null ? "" : builder.certificateVersion; + + if (builder.attributes != null) { + certificateAttributes = (CertificateAttributes) new CertificateAttributes() + .withNotBefore(builder.attributes.notBefore()).withEnabled(builder.attributes.enabled()) + .withExpires(builder.attributes.expires()); + } else { + certificateAttributes = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } 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.issuerParameters() != null) { + certificatePolicy + .withIssuerParameters(new IssuerParameters().withName(builder.policy.issuerParameters().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(); + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the certificate name + */ + public String certificateName() { + return certificateName; + } + + /** + * @return the certificate version + */ + public String certificateVersion() { + return certificateVersion; + } + + /** + * @return the certificate policy + */ + public CertificatePolicy certificatePolicy() { + return certificatePolicy; + } + + /** + * @return the certificate attributes + */ + public CertificateAttributes certificateAttributes() { + return certificateAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} 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 new file mode 100755 index 000000000000..6d62c41fc166 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java @@ -0,0 +1,193 @@ +package com.microsoft.azure.keyvault.requests; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +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. + */ +public final class UpdateKeyRequest { + + private final String vaultBaseUrl; + private final String keyName; + private final String keyVersion; + private final List keyOperations; + private final KeyAttributes keyAttributes; + private final Map tags; + + /** + * The {@link UpdateKeyRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String keyName; + + // Optional parameters + private String keyVersion; + private List keyOperations; + private KeyAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link UpdateKeyRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param keyName + * The name of the key in the given vault. + */ + public Builder(String vaultBaseUrl, String keyName) { + this.vaultBaseUrl = vaultBaseUrl; + this.keyName = keyName; + } + + /** + * The builder for constructing {@link UpdateKeyRequest} object. + * + * @param keyIdentifier + * The key identifier, e.g. + * https://{vault-name}.vault.azure.net/keys/{key-name}/{key- + * version}. + */ + public Builder(String keyIdentifier) { + KeyIdentifier id = new KeyIdentifier(keyIdentifier); + this.vaultBaseUrl = id.vault(); + this.keyName = id.name(); + this.keyVersion = id.version(); + } + + /** + * Set the key version value. + * + * @param keyVersion + * the key version. + * @return the Builder object itself. + */ + public Builder withVersion(String keyVersion) { + this.keyVersion = keyVersion; + return this; + } + + /** + * Set the key operations value. + * + * @param keyOperations + * the key operation list + * @return the Builder object itself. + */ + public Builder withKeyOperations(List keyOperations) { + this.keyOperations = keyOperations; + return this; + } + + /** + * Set the key attributes value. + * + * @param attributes + * the key management attributes value to set + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (KeyAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link UpdateKeyRequest} object. + * + * @return the {@link UpdateKeyRequest} object. + */ + public UpdateKeyRequest build() { + return new UpdateKeyRequest(this); + } + } + + private UpdateKeyRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + keyName = builder.keyName; + keyVersion = builder.keyVersion == null ? "" : builder.keyVersion; + + if (builder.keyOperations != null) { + keyOperations = new ArrayList(builder.keyOperations); + } else { + keyOperations = null; + } + + if (builder.attributes != null) { + keyAttributes = (KeyAttributes) new KeyAttributes().withEnabled(builder.attributes.enabled()) + .withExpires(builder.attributes.expires()).withNotBefore(builder.attributes.notBefore()); + } else { + keyAttributes = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vault base url + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the key name + */ + public String keyName() { + return keyName; + } + + /** + * @return the key version + */ + public String keyVersion() { + return keyVersion; + } + + /** + * @return the key operations + */ + public List keyOperations() { + return keyOperations; + } + + /** + * @return the key attributes + */ + public KeyAttributes keyAttributes() { + return keyAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} 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 new file mode 100755 index 000000000000..e56f9f7713e2 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java @@ -0,0 +1,182 @@ +package com.microsoft.azure.keyvault.requests; + +import java.util.Collections; +import java.util.Map; + +import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.keyvault.models.Attributes; +import com.microsoft.azure.keyvault.models.SecretAttributes; + +/** + * The update secret request class. + */ +public final class UpdateSecretRequest { + private final String vaultBaseUrl; + private final String secretName; + private final String secretVersion; + private final String contentType; + private final SecretAttributes secretAttributes; + private final Map tags; + + /** + * The {@link UpdateSecretRequest} builder. + */ + public static class Builder { + + // Required parameters + private final String vaultBaseUrl; + private final String secretName; + + // Optional parameters + private String secretVersion; + private String contentType; + private SecretAttributes attributes; + private Map tags; + + /** + * The builder for constructing {@link UpdateSecretRequest} object. + * + * @param vaultBaseUrl + * The vault name, e.g. https://myvault.vault.azure.net. + * @param secretName + * The name of the secret in the given vault. + */ + public Builder(String vaultBaseUrl, String secretName) { + this.vaultBaseUrl = vaultBaseUrl; + this.secretName = secretName; + } + + /** + * The builder for constructing {@link UpdateSecretRequest} object. + * + * @param secretId + * The secret identifier, e.g. + * https://{vault-name}.vault.azure.net/secrets/{secret-name} + * /{ secret-version}. + */ + public Builder(String secretId) { + SecretIdentifier id = new SecretIdentifier(secretId); + this.vaultBaseUrl = id.vault(); + this.secretName = id.name(); + this.secretVersion = id.version(); + } + + /** + * Sets the secret version. + * @param version the secret version. + * @return the Builder object itself. + */ + public Builder withVersion(String version) { + this.secretVersion = version; + return this; + } + + /** + * Set the content type value. + * + * @param contentType + * Type of the secret value such as a password. + * @return the Builder object itself. + */ + public Builder withContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Set the attributes value. + * + * @param attributes + * The secret management attributes. + * @return the Builder object itself. + */ + public Builder withAttributes(Attributes attributes) { + this.attributes = (SecretAttributes) attributes; + return this; + } + + /** + * Set the tags value. + * + * @param tags + * Application-specific metadata in the form of key-value + * pairs. + * @return the Builder object itself. + */ + public Builder withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * builds the {@link UpdateSecretRequest} object. + * + * @return the {@link UpdateSecretRequest} object. + */ + public UpdateSecretRequest build() { + return new UpdateSecretRequest(this); + } + } + + private UpdateSecretRequest(Builder builder) { + vaultBaseUrl = builder.vaultBaseUrl; + secretName = builder.secretName; + secretVersion = builder.secretVersion == null ? "" : builder.secretVersion; + contentType = builder.contentType; + + if (builder.attributes != null) { + secretAttributes = (SecretAttributes) new SecretAttributes().withNotBefore(builder.attributes.notBefore()) + .withEnabled(builder.attributes.enabled()).withExpires(builder.attributes.expires()); + } else { + secretAttributes = null; + } + + if (builder.tags != null) { + tags = Collections.unmodifiableMap(builder.tags); + } else { + tags = null; + } + } + + /** + * @return the vaultBaseUrl + */ + public String vaultBaseUrl() { + return vaultBaseUrl; + } + + /** + * @return the secretName + */ + public String secretName() { + return secretName; + } + + /** + * @return the secretVersion + */ + public String secretVersion() { + return secretVersion; + } + + /** + * @return the contentType + */ + public String contentType() { + return contentType; + } + + /** + * @return the secretAttributes + */ + public SecretAttributes secretAttributes() { + return secretAttributes; + } + + /** + * @return the tags + */ + public Map tags() { + return tags; + } +} diff --git a/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java new file mode 100755 index 000000000000..bc203912e1f9 --- /dev/null +++ b/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/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 the classes for KeyVaultClient. Performs cryptographic + * key operations and vault operations against the Key Vault service. + */ +package com.microsoft.azure.keyvault.requests; 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 000000000000..d4c47bfe7b83 --- /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.IssuerParameters; +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).body().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).body().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")) + .withIssuerParameters(new IssuerParameters().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).body().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 new file mode 100755 index 000000000000..f186fe4bf73f --- /dev/null +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java @@ -0,0 +1,1131 @@ +/** + * 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.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; +import java.security.spec.InvalidKeySpecException; +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; +import java.util.regex.Pattern; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +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.IssuerParameters; +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; +import com.microsoft.azure.keyvault.models.CertificateOperation; +import com.microsoft.azure.keyvault.models.CertificatePolicy; +import com.microsoft.azure.keyvault.models.SecretBundle; +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.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 X509 = "X.509"; + + static final String PKCS12 = "PKCS12"; + + static final String MIME_PKCS12 = "application/x-pkcs12"; + + static final String MIME_PEM = "application/x-pem-file"; + + 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 STATUS_COMPLETED = "Completed"; + + 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 _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 PAGELIST_MAX_CERTS = 3; + + 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" + IssuerParameters issuerParameters = new IssuerParameters() + .withName(ISSUER_SELF); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerParameters(issuerParameters) + .withX509CertificateProperties(x509Properties); + + Attributes attribute = new CertificateAttributes() + .withEnabled(true) + .withExpires(new DateTime().withYear(2050).withMonthOfYear(1)) + .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1)); + + String vaultUri = getVaultUri(); + String certificateName = "createSelfSignedJavaPkcs12"; + + CreateCertificateRequest createCertificateRequest = + new CreateCertificateRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicy) + .withAttributes(attribute) + .withTags(sTags) + .build(); + + CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest); + + Assert.assertNotNull(certificateOperation); + Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS)); + + CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation); + validateCertificateBundle(certificateBundle, certificatePolicy); + compareAttributes(attribute, createCertificateRequest.certificateAttributes()); + + // Load the CER part into X509Certificate object + X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle); + + Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName)); + Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName)); + + // Retrieve the secret backing the certificate + SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier(); + SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier()); + Assert.assertTrue(secret.managed()); + + // Retrieve the key backing the certificate + KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier(); + KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier()); + Assert.assertTrue(keyBundle.managed()); + + // Load the secret into a KeyStore + String secretPassword = ""; + KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword); + + // Validate the certificate and key in the KeyStore + validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword); + + CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName); + Assert.assertNotNull(deletedCertificateBundle); + try { + keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.body().error()); + Assert.assertEquals("CertificateNotFound", e.body().error().code()); + } + } + + /** + * 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" + IssuerParameters issuerParameters = new IssuerParameters() + .withName(ISSUER_SELF); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerParameters(issuerParameters) + .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.body().error()); + Assert.assertEquals("CertificateNotFound", e.body().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 + IssuerParameters issuerParameters = new IssuerParameters(); + issuerParameters.withName(createdCertificateIssuer.issuerIdentifier().name()); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerParameters(issuerParameters) + .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.body().error()); + Assert.assertEquals("CertificateNotFound", e.body().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 + IssuerParameters issuerParameters = new IssuerParameters(); + issuerParameters.withName(createdCertificateIssuer.issuerIdentifier().name()); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerParameters(issuerParameters) + .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.body().error()); + Assert.assertEquals("CertificateNotFound", e.body().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" + IssuerParameters issuerParameters = new IssuerParameters(); + issuerParameters.withName(ISSUER_UNKNOWN); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerParameters(issuerParameters) + .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.body().error()); + Assert.assertEquals("CertificateNotFound", e.body().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" + IssuerParameters issuerParameters = new IssuerParameters() + .withName(ISSUER_SELF); + + CertificatePolicy certificatePolicy = new CertificatePolicy() + .withSecretProperties(secretProperties) + .withIssuerParameters(issuerParameters) + .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.body().error()); + Assert.assertEquals("CertificateNotFound", e.body().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.withIssuerParameters(new IssuerParameters().withName(ISSUER_SELF)); + CertificatePolicy updatedCertificatePolicy = keyVaultClient.updateCertificatePolicy( + new UpdateCertificatePolicyRequest + .Builder(vaultUri, certificateName) + .withPolicy(certificatePolicyUpdate) + .build()); + Assert.assertEquals(certificatePolicyUpdate.issuerParameters().name(), updatedCertificatePolicy.issuerParameters().name()); + + CertificatePolicy policy = keyVaultClient.getCertificatePolicy(vaultUri, certificateName); + Assert.assertEquals(certificatePolicyUpdate.issuerParameters().name(), policy.issuerParameters().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.body().error().code().equals("Throttled")) { + System.out.println("Waiting to avoid throttling"); + Thread.sleep(failureCount * 1500); + continue; + } + throw e; + } + } + } + + PagedList listResult = keyVaultClient.listCertificates(getVaultUri(), PAGELIST_MAX_CERTS); + Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().items().size()); + + HashSet toDelete = new HashSet(); + + for (CertificateItem item : listResult) { + 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()); + CertificateIdentifier id = certificateBundle.certificateIdentifier(); + certificates.add(id.identifier()); + break; + } catch (KeyVaultErrorException e) { + ++failureCount; + if (e.body().error().code().equals("Throttled")) { + System.out.println("Waiting to avoid throttling"); + Thread.sleep(failureCount * 1500); + continue; + } + throw e; + } + } + } + + PagedList listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName, PAGELIST_MAX_CERTS); + Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().items().size()); + + listResult = keyVaultClient.listCertificateVersions(getVaultUri(), certificateName); + + for (CertificateItem item : listResult) { + if(item != null) { + certificates.remove(item.id()); + } + } + + Assert.assertEquals(0, certificates.size()); + + keyVaultClient.deleteCertificate(getVaultUri(), certificateName); + } + + /** + * CRUD for Certificate issuers + */ + @Test + public void issuerCrudOperations() throws Exception { + // Construct organization administrator details + AdministratorDetails administratorDetails = new AdministratorDetails() + .withFirstName("John") + .withLastName("Doe") + .withEmailAddress("john.doe@contoso.com") + .withPhone("1234567890"); + + // Construct organization details + OrganizationDetails organizationDetails = new OrganizationDetails(); + List administratorsDetails = new ArrayList(); + administratorsDetails.add(administratorDetails); + organizationDetails.withAdminDetails(administratorsDetails); + + // Construct certificate issuer credentials + IssuerCredentials credentials = new IssuerCredentials() + .withAccountId("account1") + .withPassword("Pa$$w0rd"); + + IssuerBundle certificateIssuer = new IssuerBundle() + .withProvider(ISSUER_TEST) + .withCredentials(credentials) + .withOrganizationDetails(organizationDetails); + + IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer( + new SetCertificateIssuerRequest + .Builder(getVaultUri(), "issuer1", certificateIssuer.provider()) + .withCredentials(certificateIssuer.credentials()) + .withOrganizationDetails(certificateIssuer.organizationDetails()) + .build()); + + 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.body().error()); + Assert.assertEquals("CertificateIssuerNotFound", e.body().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.body().error()); + Assert.assertEquals("ContactsNotFound", e.body().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().issuerParameters()); + Assert.assertNotNull(certificateBundle.policy().issuerParameters().name()); + if(certificatePolicy.issuerParameters() != null) { + Assert.assertTrue(certificateBundle.policy().issuerParameters().name().equalsIgnoreCase(certificatePolicy.issuerParameters().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 new file mode 100755 index 000000000000..e2613dfb99b4 --- /dev/null +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java @@ -0,0 +1,574 @@ +/** + * 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.math.BigInteger; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.MessageDigest; +import java.security.spec.KeySpec; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import javax.crypto.Cipher; + +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.Test; + +import com.microsoft.azure.keyvault.models.KeyBundle; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.keyvault.KeyIdentifier; +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.requests.CreateKeyRequest; +import com.microsoft.azure.keyvault.requests.ImportKeyRequest; +import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; +import com.microsoft.azure.keyvault.models.Attributes; +import com.microsoft.azure.keyvault.models.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; +import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; + +public class KeyOperationsTest extends KeyVaultClientIntegrationTestBase { + + private static final String KEY_NAME = "javaKey"; + private static final int MAX_KEYS = 4; + private static final int PAGELIST_MAX_KEYS = 3; + + @Test + public void transparentAuthentication() throws Exception { + + // Create a key on a vault. + { + 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, JsonWebKeyType.RSA).build()); + validateRsaKeyBundle(bundle, getSecondaryVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); + } + + } + + @Test + public void importKeyOperation() throws Exception { + + KeyBundle keyBundle = new KeyBundle(); + JsonWebKey key = JsonWebKey.fromRSA(getTestKeyMaterial()); + + key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT)); + + keyBundle.withKey(key); + + checkImportOperation(keyBundle, false); + checkImportOperation(keyBundle, true); + } + + 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) + .withAttributes(attribute) + .withTags(tags) + .build()); + + validateRsaKeyBundle(importResultBundle, getVaultUri(), KEY_NAME, importToHardware ? JsonWebKeyType.RSA_HSM : JsonWebKeyType.RSA, importedJwk.keyOps(), attribute); + checkEncryptDecryptSequence(importedJwk, importResultBundle); + Assert.assertTrue(importResultBundle.key().isValid()); + } + + private void checkEncryptDecryptSequence(JsonWebKey importedKey, KeyBundle importedKeyBundle) throws Exception { + + // Test variables + byte[] plainText = new byte[100]; + new Random(0x1234567L).nextBytes(plainText); + byte[] cipherText; + + // Encrypt in the service. + { + KeyOperationResult result = keyVaultClient.encrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); + cipherText = result.result(); + } + + // Decrypt in the client, notice OAEP algorithm instance to use. + { + Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); + cipher.init(Cipher.DECRYPT_MODE, importedKey.toRSA(true).getPrivate()); + + byte[] beforeEncrypt = plainText; + byte[] afterDecrypt = cipher.doFinal(cipherText); + Assert.assertArrayEquals(beforeEncrypt, afterDecrypt); + } + + // Encrypt in the client, using the service provided material. Also use + // standard padding. + { + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, importedKeyBundle.key().toRSA().getPublic()); + + cipherText = cipher.doFinal(plainText); + } + + // Decrypt in the service. + { + KeyOperationResult result = keyVaultClient.decrypt(importedKeyBundle.key().kid(), JsonWebKeyEncryptionAlgorithm.RSA1_5, cipherText); + + byte[] beforeEncrypt = plainText; + byte[] afterDecrypt = result.result(); + Assert.assertArrayEquals(beforeEncrypt, afterDecrypt); + } + } + + @Test + public void crudOperations() throws Exception { + + KeyBundle createdBundle; + { + // Create key + createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); + } + + // Key identifier. + KeyIdentifier keyId = new KeyIdentifier(createdBundle.key().kid()); + + { + // Get key using kid WO version + KeyBundle readBundle = keyVaultClient.getKey(keyId.baseIdentifier()); + compareKeyBundles(createdBundle, readBundle); + } + + { + // Get key using full kid as defined in the bundle + KeyBundle readBundle = keyVaultClient.getKey(createdBundle.key().kid()); + compareKeyBundles(createdBundle, readBundle); + } + + { + // Get key using vault and key name. + KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME); + compareKeyBundles(createdBundle, readBundle); + } + + { + // Get key using vault, key name and version. + KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME, keyId.version()); + compareKeyBundles(createdBundle, readBundle); + } + + { + // Get key using vault, key name and a null version. + KeyBundle readBundle = keyVaultClient.getKey(getVaultUri(), KEY_NAME); + compareKeyBundles(createdBundle, readBundle); + } + + { + // Update key using the kid as defined in the bundle + + // First we create a bundle with the modified attributes. + createdBundle.attributes().withExpires(new DateTime() + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2050)); + List key_ops = Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT); + Map tags = new HashMap(); + tags.put("foo", "baz"); + createdBundle.key().withKeyOps(key_ops); + createdBundle.withTags(tags); + + // Perform the operation. + KeyBundle updatedBundle = keyVaultClient.updateKey( + new UpdateKeyRequest + .Builder(createdBundle.key().kid()) + .withKeyOperations(key_ops) + .withAttributes(createdBundle.attributes()) + .withTags(createdBundle.tags()) + .build()); + + compareKeyBundles(createdBundle, updatedBundle); + + // Subsequent operations must use the updated bundle for comparison. + createdBundle = updatedBundle; + } + + { + // Update key using vault and key name. + + // First we create a bundle with the modified attributes. + createdBundle.attributes().withNotBefore(new DateTime() + .withMonthOfYear(2) + .withDayOfMonth(1) + .withYear(2000)); + List 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. + KeyBundle updatedBundle = keyVaultClient.updateKey( + new UpdateKeyRequest + .Builder(getVaultUri(), KEY_NAME) + .withKeyOperations(key_ops) + .withAttributes(createdBundle.attributes()) + .withTags(createdBundle.tags()) + .build()); + + compareKeyBundles(createdBundle, updatedBundle); + } + + { + // Delete key + KeyBundle deleteBundle = keyVaultClient.deleteKey(getVaultUri(), KEY_NAME); + compareKeyBundles(createdBundle, deleteBundle); + } + + { + // Expects a key not found + try { + keyVaultClient.getKey(keyId.baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.body().error()); + Assert.assertEquals("KeyNotFound", e.body().error().code()); + } + } + + } + + @Test + public void backupRestore() throws Exception { + + KeyBundle createdBundle; + + // Creates a key + { + createdBundle = keyVaultClient.createKey( + new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA) + .build()); + validateRsaKeyBundle(createdBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); + } + + // Creates a backup of key. + byte[] keyBackup; + { + keyBackup = keyVaultClient.backupKey(getVaultUri(), KEY_NAME).value(); + } + + // Deletes the key. + { + keyVaultClient.deleteKey(getVaultUri(), KEY_NAME); + } + + // Restores the key. + { + KeyBundle restoredBundle = keyVaultClient.restoreKey(getVaultUri(), keyBackup); + compareKeyBundles(createdBundle, restoredBundle); + } + + } + + @Test + public void listKeys() throws Exception { + + HashSet keys = new HashSet(); + for (int i = 0; i < MAX_KEYS; ++i) { + int failureCount = 0; + for (;;) { + try { + KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME + i, JsonWebKeyType.RSA).build()); + KeyIdentifier kid = new KeyIdentifier(createdBundle.key().kid()); + keys.add(kid.baseIdentifier()); + break; + } catch (KeyVaultErrorException e) { + ++failureCount; + if (e.body().error().code().equals("Throttled")) { + System.out.println("Waiting to avoid throttling"); + Thread.sleep(failureCount * 1500); + continue; + } + throw e; + } + } + } + + PagedList listResult = keyVaultClient.listKeys(getVaultUri(), PAGELIST_MAX_KEYS); + Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().items().size()); + + HashSet toDelete = new HashSet(); + + for (KeyItem item : listResult) { + if(item != null) { + KeyIdentifier id = new KeyIdentifier(item.kid()); + toDelete.add(id.name()); + keys.remove(item.kid()); + } + } + + Assert.assertEquals(0, keys.size()); + + for (String name : toDelete) { + try{ + keyVaultClient.deleteKey(getVaultUri(), name); + } + catch(KeyVaultErrorException e){ + // Ignore forbidden exception for certificate keys that cannot be deleted + if(!e.body().error().code().equals("Forbidden")) + throw e; + } + } + } + + @Test + public void listKeyVersions() throws Exception { + + HashSet keys = new HashSet(); + for (int i = 0; i < MAX_KEYS; ++i) { + int failureCount = 0; + for (;;) { + try { + KeyBundle createdBundle = keyVaultClient.createKey(new CreateKeyRequest.Builder(getVaultUri(), KEY_NAME, JsonWebKeyType.RSA).build()); + keys.add(createdBundle.key().kid()); + break; + } catch (KeyVaultErrorException e) { + ++failureCount; + if (e.body().error().code().equals("Throttled")) { + System.out.println("Waiting to avoid throttling"); + Thread.sleep(failureCount * 1500); + continue; + } + throw e; + } + } + } + + PagedList listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME, MAX_KEYS); + //TODO bug: Assert.assertTrue(PAGELIST_MAX_KEYS >= listResult.currentPage().getItems().size()); + + listResult = keyVaultClient.listKeyVersions(getVaultUri(), KEY_NAME); + + for (KeyItem item : listResult) { + if(item != null) { + keys.remove(item.kid()); + } + } + + Assert.assertEquals(0, keys.size()); + + keyVaultClient.deleteKey(getVaultUri(), KEY_NAME); + } + + @Test + public void encryptDecryptOperations() throws Exception { + + JsonWebKey testKey = importTestKey(); + KeyIdentifier keyId = new KeyIdentifier(testKey.kid()); + + // Test variables + byte[] plainText = new byte[100]; + new Random(0x1234567L).nextBytes(plainText); + byte[] cipherText; + + KeyOperationResult result; + + // encrypt and decrypt using kid WO version + { + result = keyVaultClient.encrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); + cipherText = result.result(); + + result = keyVaultClient.decrypt(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); + Assert.assertArrayEquals(plainText, result.result()); + } + + // encrypt and decrypt using full kid + { + result = keyVaultClient.encrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); + cipherText = result.result(); + + result = keyVaultClient.decrypt(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); + Assert.assertArrayEquals(plainText, result.result()); + } + } + + @Test + public void wrapUnwrapOperations() throws Exception { + + JsonWebKey testKey = importTestKey(); + KeyIdentifier keyId = new KeyIdentifier(testKey.kid()); + + // Test variables + byte[] plainText = new byte[100]; + new Random(0x1234567L).nextBytes(plainText); + byte[] cipherText; + + KeyOperationResult result; + + // wrap and unwrap using kid WO version + { + result = keyVaultClient.wrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); + cipherText = result.result(); + + result = keyVaultClient.unwrapKey(keyId.baseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); + Assert.assertArrayEquals(plainText, result.result()); + } + + // wrap and unwrap using full kid + { + result = keyVaultClient.wrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, plainText); + cipherText = result.result(); + + result = keyVaultClient.unwrapKey(testKey.kid(), JsonWebKeyEncryptionAlgorithm.RSA_OAEP, cipherText); + Assert.assertArrayEquals(plainText, result.result()); + } + } + + @Test + public void signVerifyOperations() throws Exception { + + JsonWebKey testKey = importTestKey(); + KeyIdentifier keyId = new KeyIdentifier(testKey.kid()); + + // Test variables + byte[] plainText = new byte[100]; + new Random(0x1234567L).nextBytes(plainText); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(plainText); + byte[] digest = md.digest(); + byte[] signature; + + KeyOperationResult result; + KeyVerifyResult verifyResult; + + // Using kid WO version + { + result = keyVaultClient.sign(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest); + signature = result.result(); + + verifyResult = keyVaultClient.verify(keyId.baseIdentifier(), JsonWebKeySignatureAlgorithm.RS256, digest, signature); + Assert.assertEquals(new Boolean(true), verifyResult.value()); + } + + // Using full kid + { + result = keyVaultClient.sign(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest); + signature = result.result(); + + verifyResult = keyVaultClient.verify(testKey.kid(), JsonWebKeySignatureAlgorithm.RS256, digest, signature); + Assert.assertEquals(new Boolean(true), verifyResult.value()); + + } + } + + private static JsonWebKey importTestKey() throws Exception { + + KeyBundle keyBundle = new KeyBundle(); + JsonWebKey key = JsonWebKey.fromRSA(getTestKeyMaterial()); + + key.withKty(JsonWebKeyType.RSA); + key.withKeyOps(Arrays.asList(JsonWebKeyOperation.ENCRYPT, JsonWebKeyOperation.DECRYPT, JsonWebKeyOperation.SIGN, JsonWebKeyOperation.VERIFY, JsonWebKeyOperation.WRAP_KEY, JsonWebKeyOperation.UNWRAP_KEY)); + + keyBundle = keyVaultClient.importKey( + new ImportKeyRequest + .Builder(getVaultUri(), KEY_NAME, key) + .withHsm(false) + .build()); + + validateRsaKeyBundle(keyBundle, getVaultUri(), KEY_NAME, JsonWebKeyType.RSA, null, null); + + return keyBundle.key(); + } + + 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 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( + String.format("\"kid\" should start with \"%s\", but instead the value is \"%s\".", prefix, kid), + kid.startsWith(prefix)); + Assert.assertEquals(kty, bundle.key().kty()); + Assert.assertNotNull("\"n\" should not be null.", bundle.key().n()); + Assert.assertNotNull("\"e\" should not be null.", bundle.key().e()); + if (key_ops != null) { + Assert.assertTrue(key_ops.equals(bundle.key().keyOps())); + } + Assert.assertNotNull("\"created\" should not be null.", bundle.attributes().created()); + Assert.assertNotNull("\"updated\" should not be null.", bundle.attributes().updated()); + + compareAttributes(attributes, bundle.attributes()); + + Assert.assertTrue(bundle.managed() == null || bundle.managed() == false); + Assert.assertTrue(bundle.key().isValid()); + } + + + + 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())); + } +} 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 new file mode 100755 index 000000000000..d3deb5fcb23f --- /dev/null +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java @@ -0,0 +1,161 @@ +/** + * 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.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; + +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.microsoft.aad.adal4j.AuthenticationContext; +import com.microsoft.aad.adal4j.AuthenticationResult; +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 { + + /** + * The client instance that should be used on tests. + */ + protected static KeyVaultClient keyVaultClient; + + /** + * Primary vault URI, used for keys and secrets tests. + */ + public static String getVaultUri() { + return getLiveVaultUri1(); + } + + /** + * Secondary vault URI, used to verify ability to transparently authenticate + * against a different resource. + */ + public static String getSecondaryVaultUri() { + return getLiveVaultUri2(); + } + + private static String getLiveVaultUri1() { + return getenvOrDefault("keyvault.vaulturi", "https://javasdktestvault.vault.azure.net"); + } + + private static String getLiveVaultUri2() { + return getenvOrDefault("keyvault.vaulturi.alt", "https://javasdktestvault2.vault.azure.net"); + } + + private static String getenvOrDefault(String varName, String defValue) { + String value = System.getenv(varName); + return value != null ? value : defValue; + } + + protected static void createKeyVaultClient() throws Exception { + keyVaultClient = new KeyVaultClient(createTestCredentials()); + } + + private static ServiceClientCredentials createTestCredentials() throws Exception { + return new KeyVaultCredentials() { + + @Override + public String doAuthenticate(String authorization, String resource, String scope) { + try { + AuthenticationResult authResult = getAccessToken(authorization, resource); + return authResult.getAccessToken(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + }; + } + + 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."); + } + + String clientKey = System.getenv("arm.clientkey"); + String username = System.getenv("arm.username"); + String password = System.getenv("arm.password"); + + AuthenticationResult result = null; + ExecutorService service = null; + try { + service = Executors.newFixedThreadPool(1); + AuthenticationContext context = new AuthenticationContext(authorization, false, service); + + Future future = null; + + if (clientKey != null && password == null) { + ClientCredential credentials = new ClientCredential(clientId, clientKey); + future = context.acquireToken(resource, credentials, null); + } + + if (password != null && clientKey == null) { + future = context.acquireToken(resource, clientId, username, password, null); + } + + if (future == null) { + throw new Exception("Missing or ambiguous credentials - please inform exactly one of arm.clientkey or arm.password in the environment settings."); + } + + result = future.get(); + } finally { + service.shutdown(); + } + + if (result == null) { + throw new RuntimeException("authentication result was null"); + } + 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; + + @BeforeClass + public static void setup() throws Exception { + createKeyVaultClient(); + jsonWriter = new ObjectMapper().writer().withDefaultPrettyPrinter(); + jsonReader = new ObjectMapper().reader(); + } + + @AfterClass + public static void cleanup() throws Exception { + } + + @Before + public void beforeTest() throws Exception { + //setupTest(getClass().getSimpleName() + "-" + "??"); + } + + @After + public void afterTest() throws Exception { + //resetTest(getClass().getSimpleName() + "-" + "??"); + } + +} \ No newline at end of file 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 new file mode 100755 index 000000000000..4ac85a20ba77 --- /dev/null +++ b/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java @@ -0,0 +1,332 @@ +/** + * 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.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.Test; + +import com.microsoft.azure.keyvault.models.Attributes; +import com.microsoft.azure.keyvault.models.KeyVaultError; +import com.microsoft.azure.keyvault.models.KeyVaultErrorException; +import com.microsoft.azure.keyvault.models.SecretAttributes; +import com.microsoft.azure.keyvault.models.SecretBundle; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.keyvault.SecretIdentifier; +import com.microsoft.azure.keyvault.models.SecretItem; +import com.microsoft.azure.keyvault.requests.SetSecretRequest; +import com.microsoft.azure.keyvault.requests.UpdateSecretRequest; + +public class SecretOperationsTest extends KeyVaultClientIntegrationTestBase { + + private static final String SECRET_NAME = "javaSecret"; + private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; + private static final int MAX_SECRETS = 4; + private static final int PAGELIST_MAX_SECRETS = 3; + + @Test + public void transparentAuthentication() throws Exception { + + // Create a secret on a vault. + { + 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()); + validateSecret(secret, getSecondaryVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); + } + + } + + @Test + public void deserializeWithExtraFieldTest() throws Exception { + String content = "{\"error\":{\"code\":\"SecretNotFound\",\"message\":\"Secret not found: javaSecret\",\"noneexisting\":true}}"; + KeyVaultError error = keyVaultClient.serializerAdapter().deserialize(content, KeyVaultError.class); + Assert.assertEquals(error.error().message(), "Secret not found: javaSecret"); + Assert.assertEquals(error.error().code(), "SecretNotFound"); + } + + @Test + // verifies the inner error on disabled secret + public void disabledSecretGet() throws Exception { + + String secretName = "disabledsecret"; + SecretBundle secret = keyVaultClient.setSecret( + new SetSecretRequest + .Builder(getVaultUri(), secretName, SECRET_VALUE) + .withAttributes(new SecretAttributes().withEnabled(false)) + .build()); + try { + keyVaultClient.getSecret(secret.id()); + Assert.fail("Should throw exception for disabled secret."); + } + catch (KeyVaultErrorException e) { + Assert.assertEquals(e.body().error().code(), "Forbidden"); + Assert.assertNotNull(e.body().error().message()); + Assert.assertNotNull(e.body().error().innerError()); + Assert.assertEquals(e.body().error().innerError().code(), "SecretDisabled"); + } + catch (Exception e) { + Assert.fail("Should throw KeyVaultErrorException for disabled secret."); + } + keyVaultClient.deleteSecret(getVaultUri(), secretName); + } + + @Test + public void crudOperations() throws Exception { + + SecretBundle secret; + { + // Create secret + secret = keyVaultClient.setSecret( + new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, SECRET_VALUE).build()); + validateSecret(secret, getVaultUri(), SECRET_NAME, SECRET_VALUE, null, null); + } + + // Secret identifier. + SecretIdentifier secretId = new SecretIdentifier(secret.id()); + + { + // Get secret using kid WO version + 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()); + compareSecrets(secret, readBundle); + } + + { + // Get secret using vault and secret name. + 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()); + 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 + + // 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()); + compareSecrets(secret, updatedSecret); + + // Subsequent operations must use the updated bundle for comparison. + secret = updatedSecret; + } + + { + // 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"); + + // Perform the operation. + SecretBundle updatedSecret = keyVaultClient.updateSecret( + 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); + compareSecrets(secret, deleteBundle); + } + + { + // Expects a secret not found + try { + keyVaultClient.getSecret(secretId.baseIdentifier()); + } catch (KeyVaultErrorException e) { + Assert.assertNotNull(e.body().error().code()); + Assert.assertEquals("SecretNotFound", e.body().error().code()); + } + } + + } + + @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()); + SecretIdentifier id = new SecretIdentifier(secret.id()); + secrets.add(id.baseIdentifier()); + break; + } catch (KeyVaultErrorException e) { + ++failureCount; + if (e.body().error().code().equals("Throttled")) { + System.out.println("Waiting to avoid throttling"); + Thread.sleep(failureCount * 1500); + continue; + } + throw e; + } + } + } + + PagedList listResult = keyVaultClient.listSecrets(getVaultUri(), PAGELIST_MAX_SECRETS); + Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().items().size()); + + HashSet toDelete = new HashSet(); + + for (SecretItem item : listResult) { + 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.body().error().code().equals("Forbidden")) + throw e; + } + } + } + + @Test + public void listSecretVersions() 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, SECRET_VALUE).build()); + secrets.add(secret.id()); + break; + } catch (KeyVaultErrorException e) { + ++failureCount; + if (e.body().error().code().equals("Throttled")) { + System.out.println("Throttled!"); + Thread.sleep(failureCount * 1500); + continue; + } + throw e; + } + } + } + + PagedList listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME, PAGELIST_MAX_SECRETS); + Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().items().size()); + + listResult = keyVaultClient.listSecretVersions(getVaultUri(), SECRET_NAME); + for (SecretItem item : listResult) { + if(item != null) { + secrets.remove(item.id()); + } + } + + Assert.assertEquals(0, secrets.size()); + + keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME); + } + + 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( // + String.format("\"id\" should start with \"%s\", but instead the value is \"%s\".", prefix, id), // + id.startsWith(prefix)); + Assert.assertEquals(value, secret.value()); + if (contentType != null) { + Assert.assertEquals(contentType, secret.contentType()); + } + 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())); + + } + +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000000..3f7e076f5fee --- /dev/null +++ b/pom.xml @@ -0,0 +1,304 @@ + + + 4.0.0 + com.microsoft.azure + 1.0.0-beta6-SNAPSHOT + azure-keyvault-parent + pom + + Microsoft Azure Key Vault SDK Parent + This package contains the parent module of Microsoft Azure Key Vault SDK. + https://github.com/Azure/azure-key-vault-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + scm:git:https://github.com/Azure/azure-key-vault-sdk-for-java + scm:git:https://github.com/Azure/azure-sdk-for-java.git + HEAD + + + + UTF-8 + + playback + + + + + microsoft + Microsoft + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + always + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + always + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + true + default + + + + + + + com.fasterxml.jackson.core + jackson-core + 2.7.2 + + + com.fasterxml.jackson.core + jackson-databind + 2.7.2 + + + com.fasterxml.jackson.core + jackson-annotations + 2.7.0 + + + commons-codec + commons-codec + 1.10 + + + io.reactivex + rxjava + 1.2.4 + + + com.microsoft.azure + azure-client-runtime + 1.0.0 + + + com.microsoft.azure + azure-client-authentication + 1.0.0-beta6 + + + com.google.guava + guava + 20.0 + + + + junit + junit + 4.12 + test + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.17 + + + com.microsoft.azure + autorest-build-tools + 1.0.0-beta6-SNAPSHOT + + + com.puppycrawl.tools + checkstyle + 6.18 + + + + checkstyle.xml + samedir=runtimes/build-tools/src/main/resources + suppressions.xml + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + true + true + -Xlint:unchecked + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/]]>
+
+
+ + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 + +
+ + + + org.apache.maven.plugins + maven-resources-plugin + 2.4.3 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + **/Test*.java + **/*Test.java + **/*Tests.java + **/*TestCase.java + + + ${testMode} + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.2 + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + com.googlecode.addjars-maven-plugin + + + addjars-maven-plugin + + [1.0.5,) + + add-jars + + + + + + + + + + + + +
+ + + run-shade-plugin + + runShadePlugin + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.1 + + + + + shade-plugin + package + + shade + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + + + + + + ./azure-keyvault + ./azure-keyvault-core + ./azure-keyvault-cryptography + ./azure-keyvault-extensions + ./azure-keyvault-webkey + +