Encrypt an Existing Virtual Machine or Disk

First set the crypto property in the VirtualMachineConfigSpec to CryptoSpecEncrypt and provide a key. The virtual machine must be powered off, with no existing snapshots.

Storage profiles must also be set to specify encryption. If the CryptoSpec is unset, but a storage profile with encryption is set, the vCenter Server automatically generates new keys and sets CryptoSpec, if the default KMS cluster has been configured.

Encrypt a virtual machine based on storage profile

void Encrypt() throws Exception {
   // Create VirtualMachineConfigSpec 
   VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
   // Create VirtualDeviceConfigSpec 
   VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec();
   // Get VirtualMachineProfileSpec for new encryption profile and name it encryptionProfile 
   VirtualMachineProfileSpec encryptionProfile = new VirtualMachineDefinedProfileSpec();
   // Get VirtualDisk for disk to be reconfigured as in com.vmware.vm.VMReconfig, name it disk 
   diskSpec.setDevice(disk);
   diskSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
   // Add encryption profile to VirtualDeviceConfigSpec 
   diskSpec.getProfile().add(encryptionProfile);
   // Create CryptoSpec for encryption 
   // Get Key Id from CryptoManager as keyId  
   // See CryptoManager for details on generating or retrieving CryptoKeyId
   CryptoSpecEncrypt cryptoSpec = new CryptoSpecEncrypt();
   cryptoSpec.setCryptoKeyId(keyId);
   // Add CryptoSpecEncrypt to diskSpec backing 
   VirtualDeviceConfigSpecBackingSpec backingSpec = new VirtualDeviceConfigSpecBackingSpec();
   backingSpec.setCrypto(cryptoSpec);
   diskSpec.setBacking(backingSpec);
   // When encrypting a VirtualDisk, the VM home needs to be encrypted also. 
   // You can choose the same key to encrypt VM home and virtual disk, or use different keys. 
   // Set cryptoSpec and profile for encrypting virtual machine home. 
   vmConfigSpec.setCrypto(cryptoSpec);
   vmConfigSpec.getVmProfile().add(encryptionProfile);
   // Set the device changes 
   vmConfigSpec.getDeviceChange().add(diskSpec);
   // Issue reconfigure - See reConfig() in com.vmware.vm.VMReconfig for how to reconfigure VM 
}