Convert/Unconvert using @DynamoDBTypeConverted Annotation

Varsha Venkatesh
2 min readOct 7, 2020

--

@DynamoDBTypeConverted annotation is used to transform data before writing and after reading from DynamoDB.

This is the ideal place to put in logic to convert data before storing to DB and un-convert back while reading data into your application.

Let’s take an example of using @DynamoDBTypeConverted to create a custom annotation that can be used to encrypt sensitive fields in the database and decrypt back when the data is read through the application. This way the sensitive data would be encrypted when engineers use DynamoDB console for any reason and the encryption key used is generated by your application and not by DynamoDB.

Note: This is different from turning on encryption at rest for the entire table

Step 1: Creating @Encrypted custom annotation in Java

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@DynamoDBTypeConverted(converter= Encrypted.Converter.class)
public @interface Encrypted {

RootKey rootKeyName();

class Converter implements DynamoDBTypeConverter<String, String>
{
private RootKey rootKey;
private EncryptionService encryptionService;

public Converter(final Class<String> targetType, final Encrypted annotation) {
this.rootKey = annotation.rootKeyName();
initEncryptionService();
}

public Converter() {
this.rootKey = null;
initEncryptionService();
}
private void initEncryptionService() {
// initialize your Encryption Service
} @Override
public String convert(final String s) {
return encryptionService.encrypt(s, this.rootKey);
}

@Override
public String unconvert(final String s) {
return encryptionService.decrypt(s, this.rootKey);
}
}
}

Step 2: Use @Encryptedin entity class to annotate sensitive fields

@DynamoDBTable(tableName="contact")
public class Contact {

@DynamoDBHashKey(attributeName="contactId")
private String id;

private String firstName;

private String lastName;

....
@Encrypted(rootKeyName = RootKey.secretField)
private String secretField;
}

This method of writing custom annotations becomes super useful in practical applications when we want the data format in the DB to be different from the data used in the application!

--

--