Dataset Viewer
Auto-converted to Parquet Duplicate
comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
fixed.
Mono<DecryptResult> decryptAsync(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Decrypt operaiton is not supported for EC key"); }
throw new UnsupportedOperationException("Decrypt operaiton is not supported for EC key");
Mono<DecryptResult> decryptAsync(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Decrypt operation is not supported for EC key"); }
class EcKeyCryptographyClient { private KeyPair keyPair; private CryptographyServiceClient serviceClient; private Provider provider; /** * Creates a EcKeyCryptographyClient that uses {@code service} to service requests * * @param serviceClient the client to use for service side cryptography operations. */ EcKeyCryptographyClient( CryptographyServiceClient serviceClient) { this.serviceClient = serviceClient; } EcKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) { this.provider = Security.getProvider("SunEC"); this.keyPair = key.toEC(key.hasPrivateKey(), provider); this.serviceClient = serviceClient; } private KeyPair getKeyPair(JsonWebKey key) { if(keyPair == null){ keyPair = key.toEC(key.hasPrivateKey()); } return keyPair; } Mono<EncryptResult> encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Encrypt operation is not supported for EC key"); } Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) { keyPair = getKeyPair(key); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (baseAlgorithm == null) { if(serviceCryptoAvailable()) { return serviceClient.sign(algorithm, digest, context); } return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } if (keyPair.getPrivate() == null){ if(serviceCryptoAvailable()) { return serviceClient.sign(algorithm, digest, context); } return Mono.error(new IllegalArgumentException("Private portion of the key not available to perform sign operation")); } Ecdsa algo = (Ecdsa) baseAlgorithm; ISignatureTransform signer = algo.createSignatureTransform(keyPair, provider); try { return Mono.just(new SignResult(signer.sign(digest), algorithm)); } catch (Exception e) { return Mono.error(e); } } Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context, JsonWebKey key) { keyPair = getKeyPair(key); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (baseAlgorithm == null) { if(serviceCryptoAvailable()) { return serviceClient.verify(algorithm, digest, signature, context); } return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } if (keyPair.getPublic() == null){ if(serviceCryptoAvailable()) { return serviceClient.verify(algorithm, digest, signature, context); } return Mono.error(new IllegalArgumentException("Public portion of the key not available to perform verify operation")); } Ecdsa algo = (Ecdsa) baseAlgorithm; ISignatureTransform signer = algo.createSignatureTransform(keyPair, provider); try { return Mono.just(new VerifyResult(signer.verify(digest, signature))); } catch (Exception e) { return Mono.error(e); } } Mono<KeyWrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey webKey) { return Mono.error(new UnsupportedOperationException("Wrap key operation is not supported for EC key")); } Mono<KeyUnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Unwrap key operation is not supported for Ec key"); } Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.Default.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return signAsync(algorithm, digest, context, key); } catch (NoSuchAlgorithmException e){ return Mono.error(e); } } Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context, JsonWebKey key) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.Default.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verifyAsync(algorithm, digest, signature, context, key); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private boolean serviceCryptoAvailable(){ return serviceClient != null ; } }
class EcKeyCryptographyClient extends LocalKeyCryptographyClient { private KeyPair keyPair; private CryptographyServiceClient serviceClient; private Provider provider; /** * Creates a EcKeyCryptographyClient that uses {@code service} to service requests * * @param serviceClient the client to use for service side cryptography operations. */ EcKeyCryptographyClient(CryptographyServiceClient serviceClient) { super(serviceClient); this.serviceClient = serviceClient; } EcKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) { super(serviceClient); this.provider = Security.getProvider("SunEC"); this.keyPair = key.toEC(key.hasPrivateKey(), provider); this.serviceClient = serviceClient; } private KeyPair getKeyPair(JsonWebKey key) { if (keyPair == null) { keyPair = key.toEC(key.hasPrivateKey()); } return keyPair; } @Override Mono<EncryptResult> encryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Encrypt operation is not supported for EC key"); } @Override @Override Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) { keyPair = getKeyPair(key); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (baseAlgorithm == null) { if (serviceCryptoAvailable()) { return serviceClient.sign(algorithm, digest, context); } return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } if (keyPair.getPrivate() == null) { if (serviceCryptoAvailable()) { return serviceClient.sign(algorithm, digest, context); } return Mono.error(new IllegalArgumentException("Private portion of the key not available to perform sign operation")); } Ecdsa algo; if (baseAlgorithm instanceof Ecdsa) { algo = (Ecdsa) baseAlgorithm; } else { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } ISignatureTransform signer = algo.createSignatureTransform(keyPair, provider); try { return Mono.just(new SignResult(signer.sign(digest), algorithm)); } catch (Exception e) { return Mono.error(e); } } @Override Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context, JsonWebKey key) { keyPair = getKeyPair(key); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (baseAlgorithm == null) { if (serviceCryptoAvailable()) { return serviceClient.verify(algorithm, digest, signature, context); } return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } else if (!(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } if (keyPair.getPublic() == null) { if (serviceCryptoAvailable()) { return serviceClient.verify(algorithm, digest, signature, context); } return Mono.error(new IllegalArgumentException("Public portion of the key not available to perform verify operation")); } Ecdsa algo; if (baseAlgorithm instanceof Ecdsa) { algo = (Ecdsa) baseAlgorithm; } else { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } ISignatureTransform signer = algo.createSignatureTransform(keyPair, provider); try { return Mono.just(new VerifyResult(signer.verify(digest, signature))); } catch (Exception e) { return Mono.error(e); } } @Override Mono<KeyWrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey webKey) { return Mono.error(new UnsupportedOperationException("Wrap key operation is not supported for EC key")); } @Override Mono<KeyUnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Unwrap key operation is not supported for Ec key"); } @Override Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return signAsync(algorithm, digest, context, key); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } @Override Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context, JsonWebKey key) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verifyAsync(algorithm, digest, signature, context, key); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private boolean serviceCryptoAvailable() { return serviceClient != null; } }
updated.
public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return client.wrapKey(algorithm, key, Context.NONE).block(); }
return client.wrapKey(algorithm, key, Context.NONE).block();
public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return wrapKey(algorithm, key, Context.NONE); }
class CryptographyClient { private CryptographyAsyncClient client; /** * Creates a KeyClient that uses {@code pipeline} to service requests * * @param client The {@link CryptographyAsyncClient} that the client routes its request through. */ CryptographyClient(CryptographyAsyncClient client) { this.client = client; } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return The requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Key getKey() { return getKeyWithResponse(Context.NONE).value(); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Key> getKeyWithResponse(Context context) { return client.getKeyWithResponse(context).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return encrypt(algorithm, plaintext, iv, authenticationData, Context.NONE); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData, Context context) { return client.encrypt(algorithm, plaintext, context, iv, authenticationData).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return The {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(algorithm, plaintext, null, null, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { return client.decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context).block(); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(algorithm, cipherText, null, null, null, Context.NONE); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { return client.sign(algorithm, digest, context).block(); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) { return client.sign(algorithm, digest, Context.NONE).block(); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verify(algorithm, digest, signature, Context.NONE); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { return client.verify(algorithm, digest, signature, context).block(); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { return client.wrapKey(algorithm, key, context).block(); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return unwrapKey(algorithm, encryptedKey, Context.NONE); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { return client.unwrapKey(algorithm, encryptedKey, context).block(); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data) { return signData(algorithm, data, Context.NONE); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { return client.signData(algorithm, data, context).block(); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return verifyData(algorithm, data, signature, Context.NONE); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { return client.verifyData(algorithm, data, signature, context).block(); } CryptographyServiceClient getServiceClient() { return client.getCryptographyServiceClient(); } }
class CryptographyClient { private final CryptographyAsyncClient client; /** * Creates a KeyClient that uses {@code pipeline} to service requests * * @param client The {@link CryptographyAsyncClient} that the client routes its request through. */ CryptographyClient(CryptographyAsyncClient client) { this.client = client; } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the key configured in the client. Prints out the returned key details.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return The requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Key getKey() { return getKeyWithResponse(Context.NONE).value(); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the key configured in the client. Prints out the returned key details.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKeyWithResponse * * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Key> getKeyWithResponse(Context context) { return client.getKeyWithResponse(context).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Prints out the encrypted content details.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return encrypt(algorithm, plaintext, iv, authenticationData, Context.NONE); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData, Context context) { return client.encrypt(algorithm, plaintext, context, iv, authenticationData).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return The {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(algorithm, plaintext, null, null, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { return client.decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context).block(); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(algorithm, cipherText, null, null, null, Context.NONE); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign-Context} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { return client.sign(algorithm, digest, context).block(); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) { return client.sign(algorithm, digest, Context.NONE).block(); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verify(algorithm, digest, signature, Context.NONE); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify-Context} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { return client.verify(algorithm, digest, signature, context).block(); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.wrap-key-Context} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { return client.wrapKey(algorithm, key, context).block(); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return unwrapKey(algorithm, encryptedKey, Context.NONE); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.unwrap-key-Context} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { return client.unwrapKey(algorithm, encryptedKey, context).block(); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data) { return signData(algorithm, data, Context.NONE); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign-data-Context} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { return client.signData(algorithm, data, context).block(); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return verifyData(algorithm, data, signature, Context.NONE); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify-data-Context} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { return client.verifyData(algorithm, data, signature, context).block(); } CryptographyServiceClient getServiceClient() { return client.getCryptographyServiceClient(); } }
That works too.
private void unpackAndValidateId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); version = (tokens.length >= 4 ? tokens[3] : null); if(Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if(Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("Key Id is invalid"); } }
if (keyId != null && keyId.length() > 0) {
private void unpackAndValidateId(String keyId) { if (ImplUtils.isNullOrEmpty(keyId)) { throw new IllegalArgumentException("Key Id is invalid"); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if (Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { throw new IllegalArgumentException("The key identifier is malformed", e); } }
class CryptographyAsyncClient { private JsonWebKey key; private CryptographyService service; private String version; private EcKeyCryptographyClient ecKeyCryptographyClient; private RsaKeyCryptographyClient rsaKeyCryptographyClient; private CryptographyServiceClient cryptographyServiceClient; private SymmetricKeyCryptographyClient symmetricKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if(!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); ecKeyCryptographyClient = new EcKeyCryptographyClient(cryptographyServiceClient); rsaKeyCryptographyClient = new RsaKeyCryptographyClient(cryptographyServiceClient); symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(cryptographyServiceClient); } private void initializeCryptoClients() { switch(key.kty()){ case RSA: case RSA_HSM: rsaKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: ecKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKey() { return withContext(context -> getKey(context)); } Mono<Response<Key>> getKey(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is not supported for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case OCT: return symmetricKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); default: throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString())); } } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case OCT: return symmetricKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Decrypt operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signAsync(algorithm, digest, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signAsync(algorithm, digest, context, key); case OCT: return symmetricKeyCryptographyClient.signAsync(algorithm, digest, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Sign operaiton is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case OCT: return symmetricKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Verify operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case EC: case EC_HSM: return ecKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case OCT: return symmetricKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", this.key.kty().toString()))); } } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case OCT: return symmetricKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signDataAsync(algorithm, data, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signDataAsync(algorithm, data, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { if (operations.contains(keyOperation)) { return true; } return false; } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if(key == null) { try { this.key = getKey().block().value().keyMaterial(); keyAvailableLocally = this.key.isValid(); } catch (HttpResponseException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: private JsonWebKey key; private final CryptographyService service; private final CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); if (!key.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (key.keyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (key.kty() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } switch (key.kty()) { case RSA: case RSA_HSM: localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKeyWithResponse() { return withContext(context -> getKeyWithResponse(context)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing the requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Key> getKey() { return getKeyWithResponse().flatMap(FluxUtil::toMono); } Mono<Response<Key>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing permission/not supported for key with id %s", key.kid()))); } return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { this.key = getKey().block().keyMaterial(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } }
because the return type is void.
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is not supported for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case OCT: return symmetricKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); default: throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString())); } }
throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString()));
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing permission/not supported for key with id %s", key.kid()))); } return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); }
class CryptographyAsyncClient { private JsonWebKey key; private CryptographyService service; private String version; private EcKeyCryptographyClient ecKeyCryptographyClient; private RsaKeyCryptographyClient rsaKeyCryptographyClient; private CryptographyServiceClient cryptographyServiceClient; private SymmetricKeyCryptographyClient symmetricKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if(!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); ecKeyCryptographyClient = new EcKeyCryptographyClient(cryptographyServiceClient); rsaKeyCryptographyClient = new RsaKeyCryptographyClient(cryptographyServiceClient); symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(cryptographyServiceClient); } private void initializeCryptoClients() { switch(key.kty()){ case RSA: case RSA_HSM: rsaKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: ecKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKey() { return withContext(context -> getKey(context)); } Mono<Response<Key>> getKey(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case OCT: return symmetricKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Decrypt operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signAsync(algorithm, digest, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signAsync(algorithm, digest, context, key); case OCT: return symmetricKeyCryptographyClient.signAsync(algorithm, digest, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Sign operaiton is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case OCT: return symmetricKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Verify operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case EC: case EC_HSM: return ecKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case OCT: return symmetricKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", this.key.kty().toString()))); } } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case OCT: return symmetricKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signDataAsync(algorithm, data, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signDataAsync(algorithm, data, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } private void unpackAndValidateId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); version = (tokens.length >= 4 ? tokens[3] : null); if(Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if(Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("Key Id is invalid"); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { if (operations.contains(keyOperation)) { return true; } return false; } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if(key == null) { try { this.key = getKey().block().value().keyMaterial(); keyAvailableLocally = this.key.isValid(); } catch (HttpResponseException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: private JsonWebKey key; private final CryptographyService service; private final CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); if (!key.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (key.keyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (key.kty() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } switch (key.kty()) { case RSA: case RSA_HSM: localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKeyWithResponse() { return withContext(context -> getKeyWithResponse(context)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing the requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Key> getKey() { return getKeyWithResponse().flatMap(FluxUtil::toMono); } Mono<Response<Key>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); } private void unpackAndValidateId(String keyId) { if (ImplUtils.isNullOrEmpty(keyId)) { throw new IllegalArgumentException("Key Id is invalid"); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if (Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { throw new IllegalArgumentException("The key identifier is malformed", e); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { this.key = getKey().block().keyMaterial(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } }
If ANNOTATION is a child of MODIFIER use getFirstToken, it does what this for loop is doing.
private boolean hasServiceClientAnnotation(DetailAST classDefToken) { final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS); for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.ANNOTATION) { continue; } final DetailAST annotationIdent = ast.findFirstToken(TokenTypes.IDENT); if (annotationIdent != null && SERVICE_CLIENT.equals(annotationIdent.getText())) { isAsync = isAsyncServiceClient(ast); return true; } } return false; }
for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
private boolean hasServiceClientAnnotation(DetailAST classDefToken) { final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS); for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.ANNOTATION) { continue; } final DetailAST annotationIdent = ast.findFirstToken(TokenTypes.IDENT); if (annotationIdent != null && SERVICE_CLIENT.equals(annotationIdent.getText())) { isAsync = isAsyncServiceClient(ast); return true; } } return false; }
class is annotated with @ServiceClient, false otherwise. */
class is annotated with @ServiceClient, false otherwise. */
This check may not trigger when it should since async class can false-positive into the check above. I think we should change this a bit by having: ``` Java if (async name) { async checks; } else if (sync name) { sync checks; } else { naming error }
private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient.", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } if (className.endsWith(ASYNC_CLIENT) && !isAsync) { log(classDefToken, String.format("Asynchronous Client, class ''%s'' must set property ''%s'' to true.", className, IS_ASYNC)); } if (className.endsWith(CLIENT) && !className.endsWith(ASYNC_CLIENT) && isAsync) { log(classDefToken, String.format("Synchronous Client, class ''%s'' must set property''%s'' to false or without the property.", className, IS_ASYNC)); } }
if (className.endsWith(ASYNC_CLIENT) && !isAsync) {
private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } }
class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */
class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */
Error message says `class must be named AsyncClient` but condition only check if name ends with this string. So, a name like `thisIsMySuperMethodAsyncClient` would be valid right? If yes, update the error message to say that `class name must end with this string.
private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient.", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } if (className.endsWith(ASYNC_CLIENT) && !isAsync) { log(classDefToken, String.format("Asynchronous Client, class ''%s'' must set property ''%s'' to true.", className, IS_ASYNC)); } if (className.endsWith(CLIENT) && !className.endsWith(ASYNC_CLIENT) && isAsync) { log(classDefToken, String.format("Synchronous Client, class ''%s'' must set property''%s'' to false or without the property.", className, IS_ASYNC)); } }
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } }
class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */
class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */
Do we want to make this if statements `else if` statements? Do we need to check all condition even after we find one as true?
private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient.", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } if (className.endsWith(ASYNC_CLIENT) && !isAsync) { log(classDefToken, String.format("Asynchronous Client, class ''%s'' must set property ''%s'' to true.", className, IS_ASYNC)); } if (className.endsWith(CLIENT) && !className.endsWith(ASYNC_CLIENT) && isAsync) { log(classDefToken, String.format("Synchronous Client, class ''%s'' must set property''%s'' to false or without the property.", className, IS_ASYNC)); } }
if (className.endsWith(CLIENT) && !className.endsWith(ASYNC_CLIENT) && isAsync) {
private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } }
class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */
class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */
If the class does not have `@ServiceClient` annotation, is it possible to terminate this custom checkstyle evaluation i.e. no more calls to `visitToken()`? If that's possible, you could simplify the other switch cases by not having to check `if (!hasServiceClientAnnotation)`
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: addImportedClassPath(token); break; case TokenTypes.CLASS_DEF: hasServiceClientAnnotation = hasServiceClientAnnotation(token); if (!hasServiceClientAnnotation) { return; } checkServiceClientNaming(token); break; case TokenTypes.CTOR_DEF: if (!hasServiceClientAnnotation) { return; } checkConstructor(token); break; case TokenTypes.METHOD_DEF: if (!hasServiceClientAnnotation) { return; } checkMethodNameBuilder(token); checkMethodNamingPattern(token); break; case TokenTypes.OBJBLOCK: if (!hasServiceClientAnnotation) { return; } checkClassField(token); break; default: break; } }
if (!hasServiceClientAnnotation) {
public void visitToken(DetailAST token) { if (isImplPackage) { return; } switch (token.getType()) { case TokenTypes.PACKAGE_DEF: String packageName = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText(); isImplPackage = packageName.contains(".implementation"); break; case TokenTypes.CLASS_DEF: hasServiceClientAnnotation = hasServiceClientAnnotation(token); if (hasServiceClientAnnotation) { checkServiceClientNaming(token); } break; case TokenTypes.CTOR_DEF: if (hasServiceClientAnnotation) { checkConstructor(token); } break; case TokenTypes.METHOD_DEF: if (hasServiceClientAnnotation) { checkMethodName(token); } break; case TokenTypes.OBJBLOCK: if (hasServiceClientAnnotation) { checkClassField(token); } break; default: break; } }
class if it returns a ''sync'' single value."; private static final Set<String> COMMON_NAMING_PREFIX_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "upsert", "set", "create", "update", "replace", "delete", "add", "get", "list" ))); private static boolean isAsync; private static boolean hasServiceClientAnnotation; private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
class ServiceClientInstantiationCheck extends AbstractCheck { private static final String SERVICE_CLIENT = "ServiceClient"; private static final String BUILDER = "builder"; private static final String ASYNC_CLIENT = "AsyncClient"; private static final String CLIENT = "Client"; private static final String IS_ASYNC = "isAsync"; private static boolean hasServiceClientAnnotation; private static boolean isAsync; private static boolean isImplPackage; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.OBJBLOCK }; } @Override public void beginTree(DetailAST root) { hasServiceClientAnnotation = false; isAsync = false; isImplPackage = false; } @Override /** * Checks if the class is annotated with annotation @ServiceClient. A class could have multiple annotations. * * @param classDefToken the CLASS_DEF AST node * @return true if the class is annotated with @ServiceClient, false otherwise. */ private boolean hasServiceClientAnnotation(DetailAST classDefToken) { final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS); for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.ANNOTATION) { continue; } final DetailAST annotationIdent = ast.findFirstToken(TokenTypes.IDENT); if (annotationIdent != null && SERVICE_CLIENT.equals(annotationIdent.getText())) { isAsync = isAsyncServiceClient(ast); return true; } } return false; } /** * Checks for public or protected constructor for the service client class. * Log error if the service client has public or protected constructor. * * @param ctorToken the CTOR_DEF AST node */ private void checkConstructor(DetailAST ctorToken) { final DetailAST modifiersToken = ctorToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED)) { log(modifiersToken, "@ServiceClient class should not have any public or protected constructor."); } } /** * Checks for public static method named 'builder'. Should avoid to use method name, 'builder'. * * @param methodDefToken the METHOD_DEF AST node */ private void checkMethodName(DetailAST methodDefToken) { final DetailAST methodNameToken = methodDefToken.findFirstToken(TokenTypes.IDENT); if (!BUILDER.equals(methodNameToken.getText())) { return; } final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (accessModifier.equals(AccessModifier.PUBLIC) && modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)) { log(modifiersToken, "@ServiceClient class should not have a public static method named ''builder''."); } } /** * Checks that the field variables in the @ServiceClient are final. ServiceClients should be immutable. * * @param objBlockToken the OBJBLOCK AST node */ private void checkClassField(DetailAST objBlockToken) { for (DetailAST ast = objBlockToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (TokenTypes.VARIABLE_DEF != ast.getType()) { continue; } final DetailAST modifiersToken = ast.findFirstToken(TokenTypes.MODIFIERS); if (!modifiersToken.branchContains(TokenTypes.FINAL)) { log(modifiersToken, String.format("The variable field ''%s'' of class ''%s'' should be final. Classes annotated with @ServiceClient are supposed to be immutable.", ast.findFirstToken(TokenTypes.IDENT).getText(), objBlockToken.getPreviousSibling().getText())); } } } /** * Checks for the class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */ private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } } /** * A function checks if the annotation node has a member key is {@code IS_ASYNC} with value equals to 'true'. * If the value equals 'true', which indicates the @ServiceClient is an asynchronous client. * If the member pair is missing. By default, it is a synchronous service client. * * @param annotationToken the ANNOTATION AST node * @return true if the annotation has {@code IS_ASYNC} value 'true', otherwise, false. */ private boolean isAsyncServiceClient(DetailAST annotationToken) { for (DetailAST ast = annotationToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR) { continue; } final DetailAST identToken = ast.findFirstToken(TokenTypes.IDENT); if (identToken == null) { continue; } if (!IS_ASYNC.equals(identToken.getText())) { continue; } final DetailAST exprToken = ast.findFirstToken(TokenTypes.EXPR); if (exprToken == null) { continue; } return exprToken.branchContains(TokenTypes.LITERAL_TRUE); } return false; } }
I found no way to do an earlier termination of tree traversal,
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: addImportedClassPath(token); break; case TokenTypes.CLASS_DEF: hasServiceClientAnnotation = hasServiceClientAnnotation(token); if (!hasServiceClientAnnotation) { return; } checkServiceClientNaming(token); break; case TokenTypes.CTOR_DEF: if (!hasServiceClientAnnotation) { return; } checkConstructor(token); break; case TokenTypes.METHOD_DEF: if (!hasServiceClientAnnotation) { return; } checkMethodNameBuilder(token); checkMethodNamingPattern(token); break; case TokenTypes.OBJBLOCK: if (!hasServiceClientAnnotation) { return; } checkClassField(token); break; default: break; } }
if (!hasServiceClientAnnotation) {
public void visitToken(DetailAST token) { if (isImplPackage) { return; } switch (token.getType()) { case TokenTypes.PACKAGE_DEF: String packageName = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText(); isImplPackage = packageName.contains(".implementation"); break; case TokenTypes.CLASS_DEF: hasServiceClientAnnotation = hasServiceClientAnnotation(token); if (hasServiceClientAnnotation) { checkServiceClientNaming(token); } break; case TokenTypes.CTOR_DEF: if (hasServiceClientAnnotation) { checkConstructor(token); } break; case TokenTypes.METHOD_DEF: if (hasServiceClientAnnotation) { checkMethodName(token); } break; case TokenTypes.OBJBLOCK: if (hasServiceClientAnnotation) { checkClassField(token); } break; default: break; } }
class if it returns a ''sync'' single value."; private static final Set<String> COMMON_NAMING_PREFIX_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "upsert", "set", "create", "update", "replace", "delete", "add", "get", "list" ))); private static boolean isAsync; private static boolean hasServiceClientAnnotation; private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
class ServiceClientInstantiationCheck extends AbstractCheck { private static final String SERVICE_CLIENT = "ServiceClient"; private static final String BUILDER = "builder"; private static final String ASYNC_CLIENT = "AsyncClient"; private static final String CLIENT = "Client"; private static final String IS_ASYNC = "isAsync"; private static boolean hasServiceClientAnnotation; private static boolean isAsync; private static boolean isImplPackage; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.OBJBLOCK }; } @Override public void beginTree(DetailAST root) { hasServiceClientAnnotation = false; isAsync = false; isImplPackage = false; } @Override /** * Checks if the class is annotated with annotation @ServiceClient. A class could have multiple annotations. * * @param classDefToken the CLASS_DEF AST node * @return true if the class is annotated with @ServiceClient, false otherwise. */ private boolean hasServiceClientAnnotation(DetailAST classDefToken) { final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS); for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.ANNOTATION) { continue; } final DetailAST annotationIdent = ast.findFirstToken(TokenTypes.IDENT); if (annotationIdent != null && SERVICE_CLIENT.equals(annotationIdent.getText())) { isAsync = isAsyncServiceClient(ast); return true; } } return false; } /** * Checks for public or protected constructor for the service client class. * Log error if the service client has public or protected constructor. * * @param ctorToken the CTOR_DEF AST node */ private void checkConstructor(DetailAST ctorToken) { final DetailAST modifiersToken = ctorToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED)) { log(modifiersToken, "@ServiceClient class should not have any public or protected constructor."); } } /** * Checks for public static method named 'builder'. Should avoid to use method name, 'builder'. * * @param methodDefToken the METHOD_DEF AST node */ private void checkMethodName(DetailAST methodDefToken) { final DetailAST methodNameToken = methodDefToken.findFirstToken(TokenTypes.IDENT); if (!BUILDER.equals(methodNameToken.getText())) { return; } final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (accessModifier.equals(AccessModifier.PUBLIC) && modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)) { log(modifiersToken, "@ServiceClient class should not have a public static method named ''builder''."); } } /** * Checks that the field variables in the @ServiceClient are final. ServiceClients should be immutable. * * @param objBlockToken the OBJBLOCK AST node */ private void checkClassField(DetailAST objBlockToken) { for (DetailAST ast = objBlockToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (TokenTypes.VARIABLE_DEF != ast.getType()) { continue; } final DetailAST modifiersToken = ast.findFirstToken(TokenTypes.MODIFIERS); if (!modifiersToken.branchContains(TokenTypes.FINAL)) { log(modifiersToken, String.format("The variable field ''%s'' of class ''%s'' should be final. Classes annotated with @ServiceClient are supposed to be immutable.", ast.findFirstToken(TokenTypes.IDENT).getText(), objBlockToken.getPreviousSibling().getText())); } } } /** * Checks for the class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client. * * @param classDefToken the CLASS_DEF AST node */ private void checkServiceClientNaming(DetailAST classDefToken) { final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText(); if (isAsync && !className.endsWith(ASYNC_CLIENT)) { log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className)); } if (!isAsync && !className.endsWith(CLIENT)) { log(classDefToken, String.format("Sync class %s must be named <ServiceName>Client.", className)); } } /** * A function checks if the annotation node has a member key is {@code IS_ASYNC} with value equals to 'true'. * If the value equals 'true', which indicates the @ServiceClient is an asynchronous client. * If the member pair is missing. By default, it is a synchronous service client. * * @param annotationToken the ANNOTATION AST node * @return true if the annotation has {@code IS_ASYNC} value 'true', otherwise, false. */ private boolean isAsyncServiceClient(DetailAST annotationToken) { for (DetailAST ast = annotationToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR) { continue; } final DetailAST identToken = ast.findFirstToken(TokenTypes.IDENT); if (identToken == null) { continue; } if (!IS_ASYNC.equals(identToken.getText())) { continue; } final DetailAST exprToken = ast.findFirstToken(TokenTypes.EXPR); if (exprToken == null) { continue; } return exprToken.branchContains(TokenTypes.LITERAL_TRUE); } return false; } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3