Aws kms encrypt/decrypt example java

What is KMS ?

KMS is a ‘Key Management System’, help you to create and manage cryptographic keys. It helps in control use of ‘cryptographic keys’ across a wide range of AWS services and in your applications.

Application can be in C#, Go, Java, Node, PHP, Python, and Ruby or you can say KMS supported languages. SDK related to all is available on AWS site.

When to Use KMS ?

KMS is to store encryption/decryption DATA keys. Further, use data keys to encrypt and decrypt, with AWS Encryption SDK.

Code Time

Gradle.xml

implementation platform('software.amazon.awssdk:bom:2.17.87')
implementation 'software.amazon.awssdk:kms'

 implementation platform('com.amazonaws:aws-java-sdk-bom:1.12.116')
 implementation 'com.amazonaws:aws-java-sdk-kms'

Java Code

@Bean
public AWSKMS kmsClient() {
   
    String apiKey = <from aws console>
    String apiSecrete = <from aws console>
    AWSCredentialsProvider credentialsProvider = null;


    AWSCredentials credentials = new BasicAWSCredentials(apiKey, apiSecrete);
    credentialsProvider = new AWSStaticCredentialsProvider(credentials);

    return AWSKMSClientBuilder.standard()
            .withCredentials(credentialsProvider)
            .withRegion(Regions.<aws region from your console>)
            .build();
}
private final AWSKMS kmsClient;

public String encrypt(String input) throws Exception {
    String kmskey = <KMS key arn from aws console>
    ByteBuffer plaintext = ByteBuffer.wrap(input.getBytes(StandardCharsets.UTF_8));
    EncryptRequest req = new EncryptRequest().withKeyId(kmskey).withPlaintext(plaintext);
    ByteBuffer ciphertext = kmsClient.encrypt(req).getCiphertextBlob();
    String data = Base64.getUrlEncoder().encodeToString(ciphertext.array());
    return data;
}
public String decrypt(String input) throws Exception {
    String kmskey = <from console>
    byte cipherBytes[] = Base64.getUrlDecoder().decode(input);
    ByteBuffer cipherBuffer = ByteBuffer.wrap(cipherBytes);
    DecryptRequest req = new DecryptRequest().withKeyId(kmskey).withCiphertextBlob(cipherBuffer);
    DecryptResult resp = kmsClient.decrypt(req);
    return new String(resp.getPlaintext().array(), Charset.forName("UTF-8"));

}

Author: Arun Singh

Learning is an Habit.