How to encrypt an object in Azure using KeyVaultClient (JAVA)

464 views Asked by At

Normally encryption happens for byte Arrays plainText.

promise = keyVaultClient.encryptAsync(keyId.getBaseIdentifier(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, plainText); 
result = promise.get(); 
cipherText = result.getResult();

Where KeyVaultClient object encrypt byte[] and returns Future.

How to encrypt an object?

1

There are 1 answers

0
Jay Gong On

You can see soucre code of encryptAsync method as below in azure keyvault java sdk:

public ServiceFuture<KeyOperationResult> encryptAsync(String keyIdentifier, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback<KeyOperationResult> serviceCallback) {
        KeyIdentifier id = new KeyIdentifier(keyIdentifier);
        return innerKeyVaultClient.encryptAsync(id.vault, id.name, id.version == null ? "" : id.version, algorithm, value, serviceCallback);
    }

Observe the parameters required in this method, and it's not difficult to find that it needs the parameters of the byte[] type, so you just have to convert object to byte[].

You can refer to the code which mentioned in the SO thread:Java Serializable Object to Byte Array.

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  out.flush();
  byte[] yourBytes = bos.toByteArray();
  ...
} finally {
  try {
    bos.close();
  } catch (IOException ex) {
    // ignore close exception
  }
}