Search code examples
javaencryptionamazon-web-serviceskey-management

AWS KMS How to use Decrypt function Java


My question might sound too obvious but I am new to Amazon KMS. After reading a lot of docs on AWS I understood that if I am using CMK directly for encryption and decryption I can directly do it by creating encrypt and decrypt request. But what I am not clear is when I generate a data key and debug using that,the documentation says I need to pass encrypted data key to decrypt API and I will get plain text key which I can use to debug text on my "OWN". I don't understand this part. Can anyone please explain this and give a small example on decryption using data keys. Thanks in advance

My Sample code:

public String decrypt(String encryptedTextString) {
    ByteBuffer encryptedText = ByteBuffer.wrap(Base64.getDecoder().decode(encryptedTextString));
    DecryptRequest req=new DecryptRequest().withCiphertextBlob(encryptedText);
    ByteBuffer plainText = client.decrypt(req).getPlaintext();
    return new String(plainText.array());
}

public String encrypt(String plainTextString) {
    ByteBuffer plainText = ByteBuffer.wrap(Base64.getDecoder().decode(plainTextString));
    EncryptRequest req = new EncryptRequest().withKeyId(new String(plainTextKey.array()))
            .withPlaintext(plainText);
    ByteBuffer encryptedText =client.encrypt(req).getCiphertextBlob();
    return new String(encryptedText.array());
}

AWSKMSCryprography() {
    this.setCredential(new ClearCredential());
    this.genrateKey();
}

private void genrateKey() {
    GenerateDataKeyRequest request = new GenerateDataKeyRequest();
    request.setKeyId(keyID);
    request.setKeySpec("AES_128");
    GenerateDataKeyResult dataKeyResult = client.generateDataKey(request);
    plainTextKey = dataKeyResult.getPlaintext();
    encryptedKey = dataKeyResult.getCiphertextBlob();

}

Solution

  • I'm new to using KMS as well but the tutorial documentation on using encrypt and decrypt is misleading with using the encrypt and decrypt methods. The API documentation for both AWSKMSClient.generateDataKey and AWSKKMSClient.encrypt point out that encrypt() is for specific use cases and a different pattern should be use for using the local key.

    A more useful example of KMS can be found in the dynamodb encryption library. Also see http://netnix.org/2015/04/19/aes-encryption-with-hmac-integrity-in-java/ for an overview of basic encryption in general.