Menu
AWS Key Management Service
Developer Guide

Encrypting and Decrypting Data

This topic discusses how to encrypt, decrypt, and re-encrypt content.

Encrypting Data

Call the Encrypt function to encrypt plaintext data.

Copy
// Encrypting content // // Input Parameters: // The function takes four parameters. // KeyId - Unique identifier for the key to be used for encryption // Plaintext - Byte buffer that contains the content to be encrypted // EncryptionContext - Authenticated data // GrantTokens - List of grant tokens // // Return Values: // The function returns a byte buffer that contains the encrypted content and the key ID // of the master key used. // // Replace the following string with a real key ID. String keyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"; ByteBuffer plaintext = ByteBuffer.wrap(new byte[]{1,2,3,4,5,6,7,8,9,0}); EncryptRequest req = new EncryptRequest().withKeyId(keyId).withPlaintext(plaintext); ByteBuffer ciphertext = kms.encrypt(req).getCiphertextBlob();

Decrypting Data

Call the Decrypt function to decrypt ciphertext. The data to decrypt must be valid ciphertext that you receive from the Encrypt function.

Copy
// Decrypting content // // Input Parameters: // The function takes three parameters. // CipherTextBlob - Ciphertext to be decrypted // EncryptionContext - Authenticated data // GrantTokens - List of grant tokens // // Return Values: // The function returns a byte buffer that contains the decrypted content. // ByteBuffer ciphertextBlob = Place your ciphertext here; DecryptRequest req = new DecryptRequest().withCiphertextBlob(ciphertextBlob); ByteBuffer plainText = kms.decrypt(req).getPlaintext();

Re-Encrypting Data Under a Different Key

Call the ReEncrypt function to encrypt previously encrypted data by using a new key. This function decrypts your ciphertext and re-encrypts it by using a different key that you specify. The function never exposes your plaintext outside of AWS KMS.

Copy
// ReEncrypt content // Input parameters: // The function takes three parameters. // CipherTextBlob - Ciphertext to be re-encrypted // SourceEncryptionContext - Authenticated data used for the original encryption // DestinationKeyId - Key identifier for the re-encrypted data // DestinationEncryptionContext - encryption context for the re-encrypted data // GrantTokens - List of grant tokens // // Return Values: // The function returns a byte buffer that contains the re-encrypted content. // ByteBuffer sourceCiphertextBlob = Place your ciphertext here; // Replace the following string with a real key ID. String destinationKeyId = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321"; ReEncryptRequest req = new ReEncryptRequest(); req.setCiphertextBlob(sourceCiphertextBlob); req.setDestinationKeyId(destinationKeyId); ByteBuffer destinationCipherTextBlob = kms.reEncrypt(req).getCiphertextBlob();