Sub topic 5
Encrypting and decrypting small payloads directly
This chapter covers the KMS Encrypt and Decrypt calls. It assumes you know basic IAM concepts (users, roles, policies), can run AWS CLI commands, and understand the difference between plaintext and ciphertext. It also assumes you have a customer managed symmetric key with the alias alias/tutorial-key, as created in the earlier chapters on key types and aliases.
What a direct call does
With a direct call, you send your data to KMS over the network. KMS encrypts it inside its hardware security modules (HSMs) and returns the ciphertext. The key material never leaves KMS in plaintext, and you never see it.
Encrypttakes a key identifier and plaintext, and returns a ciphertext blob.Decrypttakes a ciphertext blob and returns the plaintext.
This is the simplest way to use KMS, and it has one hard limit: the plaintext passed to Encrypt can be at most 4,096 bytes. That is enough for a password, an API token, a small JSON snippet or a database connection string. It is not enough for a file, a database backup or a log archive. For those you need envelope encryption, which the next chapters cover.
Encrypting with the CLI
The following commands write a small file, encrypt it, and save the ciphertext to secret.enc.
echo -n "my secret" > secret.txt
aws kms encrypt \
--key-id alias/tutorial-key \
--plaintext fileb://secret.txt \
--encryption-context purpose=demo \
--query CiphertextBlob \
--output text | base64 --decode > secret.encSome details are worth knowing:
fileb://tells the CLI to read the file as raw bytes. If you usefile://the CLI tries to treat the content as text, and in AWS CLI v2 a--plaintextvalue given as a string must be base64 encoded. Usingfileb://avoids both problems.- The CLI prints the
CiphertextBlobfield as base64 text. Thebase64 --decodestep turns it back into binary, sosecret.encholds the real ciphertext. --encryption-context purpose=demoattaches a set of key-value pairs that KMS checks again at decrypt time. The next chapter covers it in detail. For now, treat it as a label you must repeat exactly.
Decrypting with the CLI
aws kms decrypt \
--ciphertext-blob fileb://secret.enc \
--encryption-context purpose=demo \
--query Plaintext \
--output text | base64 --decodeThe command prints my secret.
Notice that you did not pass --key-id. For a symmetric key, the ciphertext blob contains metadata that records which KMS key encrypted it. KMS reads that metadata and uses the same key. You can still pass --key-id to Decrypt. If you do, KMS checks that the ciphertext was produced by that key and fails if it was not. This is a useful safeguard, because it stops your code from decrypting data that came from an unexpected key.
The caller needs permission on the key to decrypt. Knowing the ciphertext is not enough.
What happens inside the call
The diagram shows the exchange between your code and KMS.
Every call is authorized and logged. The Encrypt response also includes the full ARN of the key that was used, even when you called it with an alias.
The same calls in Python
The CLI hides base64 handling, but an SDK returns bytes directly. This snippet uses boto3:
import boto3
kms = boto3.client("kms")
CONTEXT = {"purpose": "demo"}
enc = kms.encrypt(
KeyId="alias/tutorial-key",
Plaintext=b"my secret",
EncryptionContext=CONTEXT,
)
blob = enc["CiphertextBlob"]
print("Encrypted with", enc["KeyId"])
dec = kms.decrypt(
CiphertextBlob=blob,
EncryptionContext=CONTEXT,
KeyId=enc["KeyId"],
)
print(dec["Plaintext"].decode())Here Decrypt is given the key ARN that Encrypt returned, so KMS rejects any ciphertext from a different key. Passing the key ID is the pattern to prefer in application code.
Permissions needed
Two separate actions control the two operations:
| Operation | IAM action | Typical caller |
|---|---|---|
| Encrypt | `kms:Encrypt` | A service that writes secrets |
| Decrypt | `kms:Decrypt` | A service that reads secrets |
Splitting them lets you build one-way flows. For example, a web front end can hold only kms:Encrypt so it can protect data it receives, while a back-end worker holds kms:Decrypt. A compromise of the front end does not expose stored data.
Access is granted by the key policy, optionally combined with IAM policies and grants. Those mechanisms get their own chapters.
Common errors
| Error | Likely cause |
|---|---|
| `InvalidCiphertextException` | The blob was altered, was base64 decoded twice or not at all, or the encryption context does not match. |
| `IncorrectKeyException` | You passed a `KeyId` to `Decrypt` that did not encrypt this ciphertext. |
| `AccessDeniedException` | The caller lacks `kms:Encrypt` or `kms:Decrypt` in the key policy or IAM policy. |
| `DisabledException` | The key is disabled. |
| `KMSInvalidStateException` | The key is pending deletion. |
| `ValidationException` or a size error | The plaintext is larger than 4,096 bytes. |
| `ThrottlingException` | You exceeded the request quota for the key type and Region. |
The most frequent mistake is a base64 mismatch. The CLI returns base64 text, the SDK returns raw bytes, and --ciphertext-blob expects raw bytes through fileb://. If you see InvalidCiphertextException on a ciphertext you just created, check the encoding first and the context second.
Limits and design consequences
Direct calls have trade-offs that explain why envelope encryption exists.
- Size. The 4,096-byte limit rules out anything but small values.
- Network dependency. Every encrypt and decrypt is a network request to KMS. If KMS is unreachable or throttled, your operation fails.
- Latency and cost. Each request adds round-trip time and counts toward request pricing and per-second quotas. Encrypting a million small records means a million API calls.
- Plaintext exposure in transit. Your plaintext travels to KMS over TLS. That is safe in practice, but it means the data crosses the network, which some compliance rules care about.
Direct calls fit best when values are small, rarely accessed, and few in number. Typical examples are encrypting a configuration secret once at deployment, or protecting a data key itself. For bulk data, use GenerateDataKey and encrypt locally.
Check your understanding
Exercise
A teammate runs aws kms decrypt --ciphertext-blob fileb://secret.enc --encryption-context purpose=demo and gets InvalidCiphertextException. The file was created with aws kms encrypt --encryption-context purpose=prod. What went wrong, and what is the fix?
Show answer
The encryption context at decrypt time (purpose=demo) does not match the one used at encrypt time (purpose=prod). KMS requires an exact match, so it rejects the ciphertext. Rerun decrypt with --encryption-context purpose=prod.
Exercise
You need to protect a 2 MB export file. Can you call Encrypt on it directly? What should you do instead?
Show answer
No. Encrypt accepts at most 4,096 bytes of plaintext. Use envelope encryption: call GenerateDataKey, encrypt the file locally with the returned plaintext data key, and store the encrypted data key with the ciphertext.
Exercise
Why might you pass --key-id to Decrypt for a symmetric key even though KMS can find the key from the ciphertext?
Show answer
KMS then checks that the ciphertext came from that exact key and fails if it did not. This prevents your application from decrypting data produced by an unexpected key.