What You'll Learn
- 1Describe the project, location, key ring, key, and version hierarchy that Cloud KMS exposes
- 2Explain the operational differences between CMEK, CSEK, and Google-managed encryption
- 3Create a key with a rotation schedule and apply it to a BigQuery dataset or GCS bucket
- 4Plan rotation, disable, and destroy steps so retention policy and availability stay in balance
Encryption on Google Cloud is a stack of decisions rather than a single switch, and the service you talk to most as a data engineer is Cloud KMS, which owns the keys that other services use on your behalf. Getting the hierarchy wrong shows up as a dataset nobody can read, an audit finding about unrotated keys, or a key destroyed one quarter before the retention period ended. This lesson walks the object model, separates the three key custody models, and works through the commands and code you would run in a real remediation.
The key hierarchy, from project down to version
Everything in Cloud KMS lives at a path that mirrors how you would file an insurance document. A key ring groups keys inside a region, a crypto key holds the policy and the rotation schedule, and each rotation or manual change produces a new key version that owns one immutable cryptographic material. Ciphertext always records which version encrypted it, so rotating never rewrites your data: old ciphertext keeps pointing at the old version and new writes pick the newest enabled version.
Key rings are containers with no cryptographic meaning and cannot be deleted, which makes them a poor place to mix environments. Give each environment its own ring, then separate keys by data class inside the ring, because the IAM binding that matters in an audit is the one on the individual key. A key also carries a purpose, such as encrypt and decrypt, asymmetric signing, asymmetric decryption, or MAC generation, and the purpose is permanent: to change it you create a new key.
Custody models: Google-managed, CMEK, and CSEK
The three models differ in who holds the key material and who can rotate it, and each one answers a different compliance question.
| Model | Who holds the key | Who rotates it | Typical use | Failure if the key is lost |
|---|---|---|---|---|
| Google-managed | Google, per service | Google, automatically | Default storage, dev environments | None, service re-encrypts |
| CMEK | Cloud KMS, your project | You, on your schedule | Regulated BigQuery, GCS, Pub/Sub | Resource becomes unreadable |
| CSEK | You, never stored by Google | You, on every request | Legacy systems needing direct custody | Resource becomes unreadable |
CMEK is the model data engineers use most: you reference a key version on the resource, the service agent needs encrypt and decrypt rights on that key, and Google calls KMS on every read and write. Because Google does the calls, a mistake shows up as a job that fails with a permission error rather than as corrupt data. CSEK inverts that, you send a raw key with each request and Google stores only a hash, so you own distribution, caching, and rotation across every client. Choose CMEK unless a contract explicitly demands customer-supplied keys.
Creating a key with a rotation schedule
Rotation is a property of the key, not a script you remember to run. Set a rotation period at creation and KMS mints a new version on schedule while leaving the previous versions enabled so existing ciphertext still decrypts.
from datetime import timedelta
from google.cloud import kms_v1
client = kms_v1.KeyManagementServiceClient()
ring = 'projects/p/locations/us-central1/keyRings/data-engineering'
key = client.create_crypto_key(
request={
'parent': ring,
'crypto_key_id': 'bigquery-encryption-key',
'purpose': kms_v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT,
'rotation_period': timedelta(days=90),
'version_template': {
'algorithm': kms_v1.CryptoKeyVersion.Algorithm.GOOGLE_SYMMETRIC_ENCRYPTION,
'protection_level': kms_v1.CryptoKeyVersion.ProtectionLevel.SOFTWARE,
},
'labels': {'data_class': 'regulated'},
}
)
plaintext = b'customer export row'
response = client.encrypt(request={'name': key.name, 'plaintext': plaintext})
round_trip = client.decrypt(request={'name': key.name, 'ciphertext': response.ciphertext})
assert round_trip.plaintext == plaintext
print(key.name, 'encrypted', len(response.ciphertext), 'bytes')
Two details trip people up. First, rotation only affects future encryptions, so audit evidence must show both the rotation period and a recent next_rotation_time. Second, an HSM-backed key protects material in a hardware security module, which raises cost and key creation latency while satisfying the stricter protection levels some frameworks require. For most analytics workloads software protection is sufficient and the extra cost buys nothing an auditor asks for.
Applying CMEK to BigQuery and GCS
Once a key exists, the work is granting and referencing it. The dataset takes a key name, and every table created inside inherits it.
from google.cloud import bigquery
client = bigquery.Client()
dataset = bigquery.Dataset('my-project.encrypted_dataset')
dataset.location = 'us-central1'
dataset.encryption_configuration = bigquery.EncryptionConfiguration(
kms_key_name=(
'projects/my-project/locations/us-central1/'
'keyRings/data-engineering/cryptoKeys/bigquery-encryption-key'
)
)
dataset = client.create_dataset(dataset, exists_ok=True)
print('CMEK:', dataset.encryption_configuration.kms_key_name)
# GCS bucket with CMEK, plus the grant the service agent needs
gcloud storage buckets create gs://regulated-exports \
--location=us-central1 \
--default-kms-key=projects/p/locations/us-central1/keyRings/data-engineering/cryptoKeys/bigquery-encryption-key
gcloud kms keys add-iam-policy-binding bigquery-encryption-key \
--keyring=data-engineering \
--location=us-central1 \
--member=serviceAccount:service-PROJECT_NUMBER@gs-project-accounts.iam.gserviceaccount.com \
--role=roles/cloudkms.cryptoKeyEncrypterDecrypter
That second command is the one people discover the hard way. Without it the bucket or dataset accepts writes and then fails on the first read, with an error that points at KMS rather than at a missing binding. When you enable CMEK on an existing resource, run a read test in the same change, not just a write.
Rotation, disable, and destroy are three different acts
Disabling a version stops it being used for new encryption and decryption operations, which is how you respond to a suspected compromise without touching data. Destroying is terminal: a version enters a scheduled destruction state, waits twenty-four hours by default, and then becomes permanently undecryptable, taking every byte encrypted under it along. Rotation sits between them, adding a version while leaving the old ones usable.
Retention rules therefore constrain your key lifecycle. If policy says exports live for seven years, either keep the destroying key alive for seven years or accept that the data is unrecoverable and delete it deliberately. Teams that want cryptographic erasure treat destroy as the compliance tool it is, scheduling destruction at the moment retention expires. Document which keys are eligible for destruction in the same register where you record the retention rule, because the two are inseparable.
Auditing and rehearsing the failure
Every KMS operation lands in Cloud Audit Logs: key creation, rotation, IAM changes, encrypt and decrypt calls under data access logging. Export those entries to BigQuery and you can answer who decrypted what and when, which is the question an auditor actually asks. Alert on two patterns, a key destroyed or disabled outside a change window, and a spike in decrypt volume from a service that normally reads little.
Rehearse the other failure too. Grant a colleague access to a CMEK-protected dataset, remove their key permission, and confirm the error you get; that is the error you will see during an incident if a key binding is lost by mistake. Keep the service agent bindings in Terraform rather than in a console click, and treat a missing binding as a severity one issue, because until it returns the data is intact but nobody can prove it.
Watch the bill as well, since KMS prices each cryptographic operation. A job that calls encrypt per record will spend far more than one that asks KMS for a single data key and then encrypts the batch locally, so reach for envelope encryption as soon as a workload talks to KMS inside a loop.
Common Mistakes
Destroying a key as soon as the retention period for its data ends without checking other ciphertext
Fix: List the versions and confirm which resources reference the key, since one key often encrypts several datasets.
Enabling CMEK and running only an upload test
Fix: Read the resource back in the same change, and add the service agent binding before the first write.
Rotating keys with a one-off script instead of a rotation schedule
Fix: Set the rotation period on the key so a new version appears on time and the audit trail shows a schedule rather than an operator's memory.
Best Practices
- Separate key rings by environment and keys by data class so IAM reviews stay small
- Keep rotation on the key itself and alert when next_rotation_time moves into the past
- Export KMS audit logs to BigQuery and review decrypt volume monthly
Key Takeaways
- Ciphertext records the key version that produced it, so rotation adds a version without rewriting data
- CMEK puts the key in your project and the failure mode is a permission error, not corruption
- Disabling blocks operations on a version, destroying destroys the data with it after a waiting period
- The service agent needs encrypt and decrypt rights on your key or protected resources fail on first read
Interview Questions
Q1: What is the difference between CMEK and CSEK?
With CMEK the key lives in Cloud KMS under your project, Google calls it on your behalf, and you manage rotation and IAM. With CSEK you supply the raw key with every request, Google stores only a hash of it, and you are responsible for distributing and rotating it across every client.
Q2: What happens if you destroy a key version?
After the scheduled waiting period, typically twenty-four hours, the version is destroyed and every ciphertext encrypted under it becomes permanently unrecoverable. Nothing in Google Cloud can restore it, which is why destroy doubles as cryptographic erasure and must be tied to a retention rule.
Q3: How does key rotation interact with existing data?
Rotation creates a new version and applies it to future encryptions only. Existing ciphertext keeps its original version reference and continues to decrypt, so no re-encryption job is required, though you may choose to re-encrypt gradually for hygiene.
Q4: Why does a CMEK-protected BigQuery dataset fail after a permissions change?
The service agent for BigQuery needs cryptoKeyEncrypterDecrypter on the key you attached. Remove that binding and writes and reads fail with a KMS permission error even though the data itself is untouched, so the fix is an IAM binding, not a restore.
Q5: Where do you see who decrypted a resource?
In Cloud Audit Logs, where KMS records encrypt, decrypt, and IAM operations. Data access entries for decrypt require audit logging to be enabled for that call type, so export logs to BigQuery and alert on unusual decrypt volume rather than reading them by hand.