@Override
public Map<String, String> rekey(Map<String, String> metadata) throws TransformException, DoesNotNeedRekeyException{
String oldKeyId = metadata
.get(TransformConstants.META_ENCRYPTION_KEY_ID);
if (oldKeyId == null) {
throw new TransformException(
"Metadata does not contain a master key ID");
}
if (oldKeyId.equals(masterEncryptionKeyFingerprint)) {
// This object is already using the current key.
logger.info("Object is already using the current master key");
throw new DoesNotNeedRekeyException(
"Object is already using the current master key");
}
// Make sure we have the old key
if (!idToAliasMap.containsKey(oldKeyId)) {
throw new TransformException("Master key with fingerprint "
+ oldKeyId + " not found");
}
String oldAlias = idToAliasMap.get(oldKeyId);
KeyPair oldMasterKey = getKeyPair(oldAlias);
String encodedKey = metadata.get(TransformConstants.META_ENCRYPTION_OBJECT_KEY);
if(encodedKey == null) {
throw new TransformException("Encrypted object key not found");
}
String algorithm = getEncryptionAlgorithm();
SecretKey objectKey = KeyUtils.decryptKey(encodedKey, algorithm, provider, oldMasterKey.getPrivate());
// Re-encrypt key with the current master key
KeyPair newMasterKey = getKeyPair(masterEncryptionKeyAlias);
String newKey;
try {
newKey = KeyUtils.encryptKey(objectKey, provider, newMasterKey.getPublic());
} catch (GeneralSecurityException e) {
throw new TransformException("Error encrypting key: " + e, e);
}
Map<String, String> newMetadata = new HashMap<String, String>();
newMetadata.putAll(metadata);
newMetadata.remove(TransformConstants.META_ENCRYPTION_META_SIG);