Use Encrypt with an Amazon SDK or CLI - Amazon Key Management Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use Encrypt with an Amazon SDK or CLI

The following code examples show how to use Encrypt.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

CLI
Amazon CLI

Example 1: To encrypt the contents of a file on Linux or MacOS

The following encrypt command demonstrates the recommended way to encrypt data with the Amazon CLI.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 \ --decode > ExampleEncryptedFile

The command does several things:

Uses the --plaintext parameter to indicate the data to encrypt. This parameter value must be base64-encoded.The value of the plaintext parameter must be base64-encoded, or you must use the fileb:// prefix, which tells the Amazon CLI to read binary data from the file.If the file is not in the current directory, type the full path to file. For example: fileb:///var/tmp/ExamplePlaintextFile or fileb://C:\Temp\ExamplePlaintextFile. For more information about reading Amazon CLI parameter values from a file, see Loading Parameters from a File in the Amazon Command Line Interface User Guide and Best Practices for Local File Parameters on the Amazon Command Line Tool Blog.Uses the --output and --query parameters to control the command's output.These parameters extract the encrypted data, called the ciphertext, from the command's output.For more information about controlling output, see Controlling Command Output in the Amazon Command Line Interface User Guide.Uses the base64 utility to decode the extracted output into binary data.The ciphertext that is returned by a successful encrypt command is base64-encoded text. You must decode this text before you can use the Amazon CLI to decrypt it.Saves the binary ciphertext to a file.The final part of the command (> ExampleEncryptedFile) saves the binary ciphertext to a file to make decryption easier. For an example command that uses the Amazon CLI to decrypt data, see the decrypt examples.

Example 2: Using the Amazon CLI to encrypt data on Windows

This example is the same as the previous one, except that it uses the certutil tool instead of base64. This procedure requires two commands, as shown in the following example.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob > C:\Temp\ExampleEncryptedFile.base64 certutil -decode C:\Temp\ExampleEncryptedFile.base64 C:\Temp\ExampleEncryptedFile

Example 3: Encrypting with an asymmetric KMS key

The following encrypt command shows how to encrypt plaintext with an asymmetric KMS key. The --encryption-algorithm parameter is required. As in all encrypt CLI commands, the plaintext parameter must be base64-encoded, or you must use the fileb:// prefix, which tells the Amazon CLI to read binary data from the file.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 \ --decode > ExampleEncryptedFile

This command produces no output.

  • For API details, see Encrypt in Amazon CLI Command Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/** * Encrypts the given text asynchronously using the specified KMS client and key ID. * * @param keyId the ID of the KMS key to use for encryption * @param text the text to encrypt * @return a CompletableFuture that completes with the encrypted data as an SdkBytes object */ public CompletableFuture<SdkBytes> encryptDataAsync(String keyId, String text) { SdkBytes myBytes = SdkBytes.fromUtf8String(text); EncryptRequest encryptRequest = EncryptRequest.builder() .keyId(keyId) .plaintext(myBytes) .build(); CompletableFuture<EncryptResponse> responseFuture = getAsyncClient().encrypt(encryptRequest).toCompletableFuture(); return responseFuture.whenComplete((response, ex) -> { if (response != null) { String algorithm = response.encryptionAlgorithm().toString(); logger.info("The string was encrypted with algorithm {}.", algorithm); } else { throw new RuntimeException(ex); } }).thenApply(EncryptResponse::ciphertextBlob); }
  • For API details, see Encrypt in Amazon SDK for Java 2.x API Reference.

Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

suspend fun encryptData(keyIdValue: String): ByteArray? { val text = "This is the text to encrypt by using the AWS KMS Service" val myBytes: ByteArray = text.toByteArray() val encryptRequest = EncryptRequest { keyId = keyIdValue plaintext = myBytes } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.encrypt(encryptRequest) val algorithm: String = response.encryptionAlgorithm.toString() println("The encryption algorithm is $algorithm") // Return the encrypted data. return response.ciphertextBlob } } suspend fun decryptData( encryptedDataVal: ByteArray?, keyIdVal: String?, path: String, ) { val decryptRequest = DecryptRequest { ciphertextBlob = encryptedDataVal keyId = keyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> val decryptResponse = kmsClient.decrypt(decryptRequest) val myVal = decryptResponse.plaintext // Write the decrypted data to a file. if (myVal != null) { File(path).writeBytes(myVal) } } }
  • For API details, see Encrypt in Amazon SDK for Kotlin API reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client def encrypt(self, key_id): """ Encrypts text by using the specified key. :param key_id: The ARN or ID of the key to use for encryption. :return: The encrypted version of the text. """ text = input("Enter some text to encrypt: ") try: cipher_text = self.kms_client.encrypt( KeyId=key_id, Plaintext=text.encode() )["CiphertextBlob"] except ClientError as err: logger.error( "Couldn't encrypt text. Here's why: %s", err.response["Error"]["Message"], ) else: print(f"Your ciphertext is: {cipher_text}") return cipher_text
  • For API details, see Encrypt in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require 'aws-sdk-kms' # v2: require 'aws-sdk' # ARN of the AWS KMS key. # # Replace the fictitious key ARN with a valid key ID keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab' text = '1234567890' client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.encrypt({ key_id: keyId, plaintext: text }) # Display a readable version of the resulting encrypted blob. puts 'Blob:' puts resp.ciphertext_blob.unpack('H*')
  • For API details, see Encrypt in Amazon SDK for Ruby API Reference.

Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

async fn encrypt_string( verbose: bool, client: &Client, text: &str, key: &str, out_file: &str, ) -> Result<(), Error> { let blob = Blob::new(text.as_bytes()); let resp = client.encrypt().key_id(key).plaintext(blob).send().await?; // Did we get an encrypted blob? let blob = resp.ciphertext_blob.expect("Could not get encrypted text"); let bytes = blob.as_ref(); let s = base64::encode(bytes); let mut ofile = File::create(out_file).expect("unable to create file"); ofile.write_all(s.as_bytes()).expect("unable to write"); if verbose { println!("Wrote the following to {:?}", out_file); println!("{}", s); } Ok(()) }
  • For API details, see Encrypt in Amazon SDK for Rust API reference.

For a complete list of Amazon SDK developer guides and code examples, see Using Amazon KMS with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.