CloudBrum
CloudBrum · Cloud decision-support platform
Google Cloud Security

Cloud KMS (Key Management Service)Last reviewedReading time~12 minLevelBeginner to advanced

Google Cloud · Security · Encryption key management

Cloud KMS is where Google Cloud keeps the keys that lock your data. You create keys in a key ring, choose whether they live in software, in an HSM or in a key manager outside Google, and give services such as Cloud Storage, BigQuery and Compute Engine permission to use them. That’s what CMEK (customer-managed encryption keys) means in practice. A key is never deleted outright. Its versions are scheduled for destruction, and key rings and keys stay for good, so names and locations are worth a thought before you create anything.

On this page (17 sections)

    Mind map: Cloud KMS at a glance

    Cloud KMS mind map Cloud KMS at a glance: Structure: Key ring (a location), Key, Key version; Protection level: Software, HSM (Cloud HSM), External (Cloud EKM); Purposes: Symmetric encrypt, Asymmetric sign or decrypt, MAC (HMAC); Access: Admin role, Encrypter and decrypter, Service agents; Lifecycle: Rotation schedule, Disable and restore, Scheduled destruction; CMEK: Storage, BigQuery, Cloud SQL, Autokey, Organisation policy; Evidence: Admin Activity logs, Data Access logs, Key usage tracking; Pricing: Per key version a month, Per 10,000 operations, Single-tenant HSM. Cloud KMS at a glance Managing encryption keys on Google Cloud: the main building blocks and decisions CloudBrum Cloud decision-support platform CloudBrum Key ring (a location) Key Key version Structure Software HSM (Cloud HSM) External (Cloud EKM) Protection level Symmetric encrypt Asymmetric sign or decrypt MAC (HMAC) Purposes Admin role Encrypter and decrypter Service agents Access Rotation schedule Disable and restore Scheduled destruction Lifecycle Storage, BigQuery, Cloud SQL Autokey Organisation policy CMEK Admin Activity logs Data Access logs Key usage tracking Evidence Per key version a month Per 10,000 operations Single-tenant HSM Pricing Cloud KMS17-point analysis CloudBrum· 17-point cloud service analysis cloudbrum.com
    CloudBrum Cloud KMS at a glance · 17-point analysis Structure Key ring (a location) Key Key version Protection level Software HSM (Cloud HSM) External (Cloud EKM) Purposes Symmetric encrypt Asymmetric sign or decrypt MAC (HMAC) Access Admin role Encrypter and decrypter Service agents Lifecycle Rotation schedule Disable and restore Scheduled destruction CMEK Storage, BigQuery, Cloud SQL Autokey Organisation policy Evidence Admin Activity logs Data Access logs Key usage tracking Pricing Per key version a month Per 10,000 operations Single-tenant HSM CloudBrum · cloudbrum.com

    Free to share. The downloaded image includes the CloudBrum link.

    Key features (summary)

    • Key rings, keys and versionsA key ring sits in one location and holds keys. A key holds versions, and each version carries the actual key material. Rotating a key adds a version, and older versions stay available for decryption.
    • Three protection levelsSoftware keys are the simplest and cheapest. HSM keys are created and used in Google’s hardware security modules. External keys stay in a key manager you run outside Google and are used through Cloud EKM.
    • CMEK across Google CloudCloud Storage, BigQuery, Compute Engine disks, Cloud SQL and many other services can encrypt their data with a key you control, instead of one that Google manages for you.
    • Roles that separate the workThe admin role can manage keys but can’t encrypt or decrypt with them. Separate roles allow encrypting, decrypting, signing and viewing, so the people who run the keys don’t see the data.
    • Automatic rotationGive a symmetric key a rotation period, and Cloud KMS creates a new primary version on schedule. Data keeps working because the old versions remain enabled.
    • AutokeyWith Autokey, developers ask for a key when they create a protected resource, and Cloud KMS creates the key ring and key in a project the security team controls, using the same pattern each time.
    • Import and different purposesBesides symmetric encryption there are asymmetric keys for decrypting and signing, MAC keys, and the option to import key material that you generated yourself.
    • Logs and organisation policyAdmin Activity logs record key management. Data Access logs, which are off by default, can record each cryptographic call. Organisation policy constraints can require CMEK and limit which projects hold the keys.

    Basic concepts

    Key ring
    A named group of keys in one project and location. Key rings can’t be renamed or deleted, and a key can’t be moved to another one.
    Key (CryptoKey)
    A named resource that has a purpose, an algorithm, a protection level and a set of versions. You use the key’s name in requests, and KMS chooses the primary version.
    Key version
    A particular piece of key material. States include enabled, disabled, scheduled for destruction and destroyed.
    Primary version
    For a symmetric key, the version that is used to encrypt new data. Rotation changes the primary and leaves older versions available.
    Protection level
    Software, HSM or external. It’s chosen when the key is created and decides where the key material lives.
    Cloud HSM
    Google’s HSM-backed protection level. The service is managed for you, and a single-tenant option exists for dedicated instances.
    Cloud EKM
    External Key Manager. The key material stays in a supported key manager outside Google, and Cloud KMS calls it for each operation.
    CMEK
    Customer-managed encryption keys. A Google Cloud service encrypts your data under a Cloud KMS key that you own, rather than a Google-managed one.
    Autokey
    A way to create CMEK keys on demand, following a standard pattern, when someone makes a supported resource.
    Service agent
    A Google-managed identity for a service in your project. It needs permission on the key before the service can use CMEK.
    Scheduled destruction
    The state a key version enters when you destroy it. The material is kept for a waiting period, 30 days by default, and can be restored before it ends.
    Additional authenticated data (AAD)
    Extra, non-secret data bound to an encryption request. Decryption fails unless the same value is given again.
    Import job
    A resource that lets you bring your own key material into Cloud KMS, wrapped for transport.

    How to create & configure it

    Create a key and use it with the gcloud CLI

    1. Choose a project and locationDecide which project will hold the keys. Many teams use a dedicated key project, so the people who run keys and the people who run workloads are different. Create the key ring in the same location as the data, because most CMEK integrations need that.
    2. Create the key ring and the keyRun gcloud kms keyrings create, then gcloud kms keys create with the purpose, protection level, a rotation period and a destruction delay. These choices can’t be changed later for the key.
    3. Split administrators from usersGive the admin role to a small group, and the encrypter and decrypter roles to the service accounts and agents that use the key. Use IAM conditions or a role on one key, not on the whole project.
    4. Let a service use the keyFor CMEK on a service such as Cloud Storage, find the service agent in the project and give it the encrypter and decrypter role on the key. Then set the key as the resource’s default.
    5. Use it from codeFor small values, call encrypt and decrypt with additional authenticated data. For larger ones, generate a data key locally, encrypt the data with it and encrypt the data key with KMS.
    6. Turn on the logsAdmin Activity logs are always on. Enable Data Access audit logs for Cloud KMS, so cryptographic calls are recorded, and send them to a sink you protect.
    7. Add the guardrailsSet organisation policy constraints that require CMEK for the services you care about and limit which projects may hold keys. Consider Autokey where teams create many resources.
    8. Plan rotation and retirementCheck that automatic rotation is on, understand which data stays under old versions, and treat destroying a version as a decision with consequences.
    9. Practise a restoreDisable a test key version, see what stops, enable it again, and rehearse restoring a version that is scheduled for destruction.

    Tip: pick key ring names carefully. A key ring and a key can’t be deleted, so an experiment leaves a permanent name behind. Use a throwaway project for the first run. See the code references for the same setup as Terraform.

    Common issues after configuration

    SymptomLikely causeWhat to check / fix
    PERMISSION_DENIED: Permission 'cloudkms.cryptoKeyVersions.useToEncrypt' deniedThe caller or the service agent lacks the encrypter or decrypter role on that keyGrant roles/cloudkms.cryptoKeyEncrypterDecrypter on the key to the right principal. For CMEK, check the service agent, not your own user.
    A CMEK setup fails with a location mismatchThe key’s location doesn’t match the resource’s locationCreate the key ring in the same region as the data, or use the location that the service documents for CMEK.
    FAILED_PRECONDITION: ... key version is disabled or destroyedThe primary or required version isn’t enabledList the versions, enable the right one or restore a version that’s scheduled for destruction before the period ends.
    RESOURCE_EXHAUSTED or 429 on cryptographic requestsThe project’s per-minute quota for that key type was reached, often by many small callsUse envelope encryption, cache data keys, retry with backoff, and request a quota increase if the load is legitimate.
    Can’t delete a key ring or a keyCloud KMS doesn’t delete key rings or keysDestroy the versions you don’t need and leave the key disabled. Choose names that you can live with.
    Data is unreadable after a destroyed key versionThe version was destroyed and the waiting period endedRestore it within the waiting period. After that, only a copy of imported key material or a backup of the data under another key can help.
    An organisation policy blocks creating a resourcegcp.restrictNonCmekServices requires a CMEK key, or the key sits in a project the policy doesn’t allowProvide a key from an allowed project, or ask for an exception with a reason.
    The audit log has no record of decrypt callsData Access audit logs for Cloud KMS are off by defaultEnable them for cloudkms.googleapis.com and route them to a log bucket or sink.
    Autokey keys appear but nobody can use themThe resource’s service agent wasn’t granted use of the key, or the folder’s Autokey configuration points to a wrong projectCheck the Autokey configuration on the folder and the IAM bindings that Autokey created, and the key project’s permissions.
    A key was created with the wrong protection levelThe protection level is fixed at creationCreate a new key with the right level and re-encrypt the data. Plan the change, because the old key stays.
    A very large encrypt call failsThe plaintext is bigger than the limit for a direct call (64 KiB)Encrypt a data key with KMS and the data with that key locally.

    Use cases: when and where to use it

    Good fit

    • Teams on Google Cloud that must hold the keys for Cloud Storage, BigQuery, Cloud SQL or disks
    • Organisations that need to show a separation between key administrators and data users
    • Workloads that need HSM-protected keys without running HSMs
    • Regulated data that must be protected by a key that stays outside Google (Cloud EKM)
    • Signing tokens, documents or artifacts with asymmetric keys
    • Companies that want key creation to follow one pattern across many projects (Autokey)

    Consider something else

    • Passwords, tokens and API keys → Secret Manager, which is a separate service and can itself use a KMS key
    • TLS certificates → Certificate Manager
    • A dedicated HSM under your own control → the single-tenant Cloud HSM option
    • Encryption inside the app only, with no cloud key → a client library such as Tink, with your own key handling
    • The same job on other clouds → compare AWS KMS and Azure Key Vault

    Pros: why consider it?

    Why teams choose it

    • Simple key ring, key and version model, with clear IAM roles
    • Admin role can’t use the keys, which gives separation of duties out of the box
    • Software, HSM and external protection behind one API
    • Broad CMEK support, with organisation policies to enforce it
    • Autokey removes much of the manual setup
    • Per-version pricing keeps software keys very cheap

    Trade-offs to weigh

    • Key rings and keys can’t be deleted, so mistakes stay in the project
    • Location and protection level are fixed once the key exists
    • HSM and external keys cost much more than software ones
    • Quotas on HSM and external operations need planning
    • Secrets and certificates need other services
    • Data Access audit logs must be switched on by hand

    Common threats, vulnerabilities & risks

    RiskSeverityWhy it mattersMitigation
    Destroying a key version that still protects dataHighAfter the waiting period the material is gone, and so is anything encrypted under it.Disable first, watch for failures, keep the 30-day default and restrict who holds the destroy permission.
    The same people administer keys and use themHighIf one identity can do both, the key no longer protects data from that person.Give the admin role and the encrypter and decrypter roles to different groups, and keep the keys in their own project.
    Broad roles at the project or folder levelHighA role at a high level lets the principal use every key below it.Grant the roles on individual keys or key rings, and review them regularly.
    CMEK not enforcedMediumTeams create resources with Google-managed keys, and nothing proves that they were meant to.Set the CMEK organisation policy constraints and use Autokey to make the compliant way the easy way.
    No rotation or a forgotten scheduleMediumKey material stays in use for years, and checks for rotation fail.Set a rotation period when you create the key, and check it with an inventory script or a policy.
    One key for everythingMediumA single key is a large blast radius and a single quota domain.Use keys per application, environment and data class.
    Data Access logs are offMediumYou can’t show who decrypted data, or spot a sudden rise in use.Enable Data Access audit logs for Cloud KMS and alert on unusual volumes.
    Key location doesn’t match the dataLow–MedCMEK setup fails, or a service uses a key in a distant location with higher latency.Decide locations first, and keep keys in the same region as the data.
    An external key manager outageLow–MedWith Cloud EKM, the data can’t be read when the external manager is unreachable.Treat the external manager as part of the workload’s availability, and test the failure.

    Performance optimisation

    • Use envelope encryption and cache data keys for a short time, so busy services don’t call KMS for each record.
    • Keep the key in the same location as the workload, since every call crosses the network.
    • Choose symmetric keys for bulk work, because asymmetric operations are slower and cost more.
    • Use software keys for high-volume CMEK where policy allows. Google doesn’t apply quotas to software keys used for CMEK in its integrations.
    • Plan for the quotas on HSM and external keys, and request increases before a launch.
    • Retry with backoff on 429 and UNAVAILABLE errors, and let the client library do it.
    • Use Private Google Access or Private Service Connect for calls from private networks.
    • Reuse client objects in code, since creating a client for each call adds setup time.

    Reduce monthly cost

    FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Cloud KMS.

    • Know that software key versions cost cents a month, while HSM versions cost around a dollar or more, and external versions several dollars.
    • Use software keys where policy allows, and HSM keys where a rule requires them.
    • Remember that every active version is billed, so destroy old versions you don’t need after rotation.
    • Keep rotation periods reasonable, because each rotation adds a version that stays active.
    • Cache and use envelope encryption so that operation charges stay low.
    • Look closely at the single-tenant Cloud HSM option, which is billed per instance whatever the usage.
    • Check the free allowance on the pricing page, since it applies to specific key versions.
    • Avoid creating a key for every object or customer, which multiplies version charges.
    • Review Data Access log volume: ingesting and storing those logs is billed separately from the keys, and a busy workload makes a lot of calls.
    • Use labels on keys and a budget alert on the key project.

    Prices come from Google's pricing page and secondary sources as we read them in October 2026, and they differ by region and change over time. Check the live page before you plan around them (see Pricing).

    Security optimisation

    • Hold keys in a dedicated key project that workload teams can’t administer.
    • Give the admin role and the encrypter and decrypter roles to different groups, and grant them on single keys.
    • Require CMEK with the organisation policy constraints, and limit key projects with gcp.restrictCmekCryptoKeyProjects.
    • Set a rotation period on every symmetric key, and use a long scheduled-destruction delay.
    • Use HSM or external protection where a rule demands it, and know the availability trade-off of external keys.
    • Enable Data Access audit logs for Cloud KMS, and send them to a protected sink.
    • Use additional authenticated data so ciphertext is tied to a tenant or record.
    • Restrict who can destroy key versions and who can change IAM on keys.
    • Use VPC Service Controls around projects that hold keys and the services that use them.
    • Review service agent bindings regularly, because they grant a Google service use of your key.

    Governance & compliance

    Guardrails

    • A Terraform module for key rings and keys with rotation, a destruction delay, labels and prevent_destroy
    • Organisation policy constraints that require CMEK for chosen services and limit which projects may hold keys
    • An IAM design: admins, users and auditors as three separate groups, with roles granted on keys
    • A standard for protection levels by data class, and an owner for every key ring

    Continuous checks (organisation policy and Security Command Center)

    • “constraints/gcp.restrictNonCmekServices” to require CMEK for named services
    • “constraints/gcp.restrictCmekCryptoKeyProjects” to limit which projects may supply keys
    • Security Command Center findings for keys without rotation or with public IAM bindings
    • Cloud Asset Inventory queries for keys with no rotation period or the wrong protection level
    • Log-based alerts on key version destruction and IAM changes

    Cloud Audit Logs record key management (always) and cryptographic operations (when you enable Data Access logs), organisation policy enforces the CMEK rules above, Security Command Center reports findings, and the Compliance Resource Center holds audit reports. Google runs the service and the HSMs, and says that its HSMs carry a FIPS 140 Level 3 validation, so check the certificate list for the current version. You own the IAM design, the protection level, the rotation settings and the decision to destroy.

    Reduce carbon footprint

    • Cache data keys and use envelope encryption, so fewer requests travel to the service.
    • Use software keys where policy allows, as they use less specialised hardware.
    • Destroy old key versions and unused test keys.
    • Keep audit log volume to what you need, with a sensible retention period.
    • Where data rules allow and latency doesn’t matter, pick a region with lower grid emissions.
    • Google’s Carbon Footprint report breaks emissions down by project and service. Look for Cloud KMS in it before you publish a figure.

    Pricing

    Purchase options

    Software keys From $0.06 per key version a month

    The cheapest level. Billed for each active key version, plus a charge per 10,000 operations.

    HSM keys (Cloud HSM) From $1.00 per key version a month

    RSA 3072, RSA 4096 and elliptic curve HSM keys are listed at a higher rate for the first versions. Operations on asymmetric keys cost more.

    External keys (Cloud EKM) About $3.00 per key version a month

    The external key manager has its own bill on top of this.

    Operations and single-tenant HSM From $0.03 per 10,000 operations

    Symmetric and HMAC operations are the cheapest. A single-tenant Cloud HSM instance is billed per instance each month and is listed at about $3,500. Check the pricing page for what that includes.

    What you actually pay for

    • Every active key version each month, by protection level
    • Cryptographic operations, grouped in blocks of 10,000
    • Single-tenant Cloud HSM instances, if you use them
    • External key manager costs outside Google, for Cloud EKM
    • Log storage and ingestion for audit logs

    Rates change over time, and the pricing page lists a small monthly allowance that applies only to certain keys. See the official Cloud KMS pricing page and the Google Cloud pricing calculator.

    Important code references

    A key for an orders service: a key ring in the Mumbai region, a symmetric HSM key with a 90-day rotation and a 30-day destruction delay, an admin group that can’t use the key and a service account that can only encrypt and decrypt, plus a Cloud Storage bucket that uses the key as its default. The gcloud tab creates it and Terraform builds the same set. The Python tab does envelope encryption: it encrypts a random data key with KMS and the payload locally, and the C# tab audits every key in a location for rotation, protection level and destruction delay. Replace the project, group and service account with your own, and use a throwaway project for the first run, because key rings and keys can’t be deleted.

    # Placeholders: replace the project, group and service account with your own. Key rings and keys cannot be deleted, so try this in a throwaway project.
    PROJECT=my-keys-project
    LOCATION=asia-south1
    RING=orders
    KEY=orders-data
    APP_SA=orders-app@my-workloads-project.iam.gserviceaccount.com
    ADMIN_GROUP=group:orders-key-admins@example.com
    
    gcloud services enable cloudkms.googleapis.com --project=$PROJECT
    
    # 1. A key ring in the same location as the data, and an HSM key that rotates every 90 days.
    gcloud kms keyrings create $RING --location=$LOCATION --project=$PROJECT
    gcloud kms keys create $KEY --keyring=$RING --location=$LOCATION --project=$PROJECT \
      --purpose=encryption --protection-level=hsm \
      --rotation-period=90d --next-rotation-time="$(date -u -d '+90 days' +%Y-%m-%dT%H:%M:%SZ)" \
      --destroy-scheduled-duration=30d
    
    # 2. Administrators manage the key but cannot use it. The app can use it but cannot manage it.
    gcloud kms keys add-iam-policy-binding $KEY --keyring=$RING --location=$LOCATION --project=$PROJECT \
      --member=$ADMIN_GROUP --role=roles/cloudkms.admin
    gcloud kms keys add-iam-policy-binding $KEY --keyring=$RING --location=$LOCATION --project=$PROJECT \
      --member=serviceAccount:$APP_SA --role=roles/cloudkms.cryptoKeyEncrypterDecrypter
    
    # 3. A small value through the API. Anything larger than 64 KiB needs envelope encryption (see the Python tab).
    echo -n "order-1042" > plain.txt
    gcloud kms encrypt --key=$KEY --keyring=$RING --location=$LOCATION --project=$PROJECT \
      --plaintext-file=plain.txt --ciphertext-file=cipher.bin --additional-authenticated-data-file=<(echo -n "tenant=acme")
    gcloud kms decrypt --key=$KEY --keyring=$RING --location=$LOCATION --project=$PROJECT \
      --ciphertext-file=cipher.bin --plaintext-file=-  --additional-authenticated-data-file=<(echo -n "tenant=acme")
    
    # 4. CMEK on a bucket: the Cloud Storage service agent must be allowed to use the key.
    STORAGE_AGENT=$(gcloud storage service-agent --project=my-workloads-project)
    gcloud kms keys add-iam-policy-binding $KEY --keyring=$RING --location=$LOCATION --project=$PROJECT \
      --member=serviceAccount:$STORAGE_AGENT --role=roles/cloudkms.cryptoKeyEncrypterDecrypter
    gcloud storage buckets create gs://orders-prod-data-example --project=my-workloads-project --location=$LOCATION \
      --default-encryption-key=projects/$PROJECT/locations/$LOCATION/keyRings/$RING/cryptoKeys/$KEY
    
    # 5. Look at the versions, rotate by hand, and drill a recovery.
    gcloud kms keys versions list --key=$KEY --keyring=$RING --location=$LOCATION --project=$PROJECT
    gcloud kms keys versions create --key=$KEY --keyring=$RING --location=$LOCATION --project=$PROJECT --primary
    gcloud kms keys versions destroy 1 --key=$KEY --keyring=$RING --location=$LOCATION --project=$PROJECT
    gcloud kms keys versions restore 1 --key=$KEY --keyring=$RING --location=$LOCATION --project=$PROJECT
    # Placeholders: pass in your own projects, group and service account.
    variable "key_project" {
      type = string
    }
    
    variable "workload_project" {
      type = string
    }
    
    variable "location" {
      type    = string
      default = "asia-south1"
    }
    
    variable "admin_group" {
      type    = string
      default = "group:orders-key-admins@example.com"
    }
    
    variable "app_service_account" {
      type = string
    }
    
    resource "google_project_service" "kms" {
      project = var.key_project
      service = "cloudkms.googleapis.com"
    }
    
    resource "google_kms_key_ring" "orders" {
      project  = var.key_project
      name     = "orders"
      location = var.location
    
      depends_on = [google_project_service.kms]
    }
    
    resource "google_kms_crypto_key" "data" {
      name                       = "orders-data"
      key_ring                   = google_kms_key_ring.orders.id
      purpose                    = "ENCRYPT_DECRYPT"
      rotation_period            = "7776000s"   # 90 days
      destroy_scheduled_duration = "2592000s"   # 30 days
    
      version_template {
        algorithm        = "GOOGLE_SYMMETRIC_ENCRYPTION"
        protection_level = "HSM"
      }
    
      labels = {
        app = "orders"
        env = "prod"
      }
    
      lifecycle {
        prevent_destroy = true
      }
    }
    
    resource "google_kms_crypto_key_iam_member" "admins" {
      crypto_key_id = google_kms_crypto_key.data.id
      role          = "roles/cloudkms.admin"
      member        = var.admin_group
    }
    
    resource "google_kms_crypto_key_iam_member" "app" {
      crypto_key_id = google_kms_crypto_key.data.id
      role          = "roles/cloudkms.cryptoKeyEncrypterDecrypter"
      member        = "serviceAccount:${var.app_service_account}"
    }
    
    data "google_storage_project_service_account" "gcs" {
      project = var.workload_project
    }
    
    resource "google_kms_crypto_key_iam_member" "storage_agent" {
      crypto_key_id = google_kms_crypto_key.data.id
      role          = "roles/cloudkms.cryptoKeyEncrypterDecrypter"
      member        = "serviceAccount:${data.google_storage_project_service_account.gcs.email_address}"
    }
    
    resource "google_storage_bucket" "data" {
      project                     = var.workload_project
      name                        = "orders-prod-data-example"
      location                    = upper(var.location)
      uniform_bucket_level_access = true
    
      encryption {
        default_kms_key_name = google_kms_crypto_key.data.id
      }
    
      depends_on = [google_kms_crypto_key_iam_member.storage_agent]
    }
    
    output "key_id" {
      value = google_kms_crypto_key.data.id
    }
    # pip install google-cloud-kms cryptography
    # Envelope encryption: KMS encrypts a random data key, AES-GCM encrypts the payload locally,
    # and only the encrypted data key is stored with the ciphertext.
    import os
    
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    from google.cloud import kms
    
    client = kms.KeyManagementServiceClient()
    KEY = client.crypto_key_path("my-keys-project", "asia-south1", "orders", "orders-data")
    
    
    def encrypt(payload, tenant):
        aad = ("tenant=%s" % tenant).encode()
        data_key = AESGCM.generate_key(bit_length=256)
        wrapped = client.encrypt(request={"name": KEY, "plaintext": data_key, "additional_authenticated_data": aad})
        nonce = os.urandom(12)
        return {"key_version": wrapped.name, "wrapped_key": wrapped.ciphertext.hex(), "nonce": nonce.hex(),
                "data": AESGCM(data_key).encrypt(nonce, payload, aad).hex(), "tenant": tenant}
    
    
    def decrypt(envelope):
        aad = ("tenant=%s" % envelope["tenant"]).encode()
        plain = client.decrypt(request={"name": KEY, "ciphertext": bytes.fromhex(envelope["wrapped_key"]),
                                        "additional_authenticated_data": aad})
        return AESGCM(plain.plaintext).decrypt(bytes.fromhex(envelope["nonce"]), bytes.fromhex(envelope["data"]), aad)
    
    
    if __name__ == "__main__":
        sealed = encrypt(b'{"order": 1042, "card_last4": "4242"}', "acme")
        print("encrypted under:", sealed["key_version"])
        print("read back:", decrypt(sealed).decode())
    // dotnet add package Google.Cloud.Kms.V1
    // Audits every key in one location: purpose, protection level, rotation schedule and destruction delay.
    using Google.Cloud.Kms.V1;
    
    var client = KeyManagementServiceClient.Create();
    string project = args.Length > 0 ? args[0] : "my-keys-project";
    string location = args.Length > 1 ? args[1] : "asia-south1";
    string parent = $"projects/{project}/locations/{location}";
    int problems = 0;
    
    foreach (KeyRing ring in client.ListKeyRings(parent))
    {
        foreach (CryptoKey key in client.ListCryptoKeys(ring.Name))
        {
            var notes = new List<string>();
            bool symmetric = key.Purpose == CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt;
    
            if (symmetric && key.RotationPeriod is null) notes.Add("no rotation period");
            if (key.DestroyScheduledDuration is { } d && d.ToTimeSpan() < TimeSpan.FromDays(30)) notes.Add($"destruction delay is only {d.ToTimeSpan().TotalDays:0} day(s)");
            if (key.Primary is null && symmetric) notes.Add("no primary version");
            if (key.Primary?.State != CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled && key.Primary is not null) notes.Add($"primary version is {key.Primary.State}");
    
            string level = key.VersionTemplate?.ProtectionLevel.ToString() ?? key.Primary?.ProtectionLevel.ToString() ?? "unknown";
            Console.WriteLine($"{key.CryptoKeyName.KeyRingId}/{key.CryptoKeyName.CryptoKeyId,-24} {key.Purpose,-16} {level,-9} rotation={(key.RotationPeriod?.ToTimeSpan().TotalDays.ToString("0") ?? "none")}d");
            foreach (string n in notes) { Console.WriteLine($"    ! {n}"); problems++; }
        }
    }
    
    Console.WriteLine(problems == 0 ? "No problems found." : $"{problems} problem(s) found.");
    return problems == 0 ? 0 : 1;

    Best videos to explore

    Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.

    Introducing Google Cloud Key Management ServiceOfficial · Google Cloud · Beginner · Watch on YouTube
    Getting Started with Cloud KMSCommunity video · Beginner · Watch on YouTube
    GCP KMS ExplainedCommunity video · Intermediate · Watch on YouTube
    Using Customer Managed Encryption Keys with Cloud Storage and Cloud KMSCommunity video · Advanced · Watch on YouTube

    Interview questions

    BasicWhat is Cloud KMS?

    It’s Google Cloud’s service for creating and using cryptographic keys. You keep keys in key rings, choose software, HSM or external protection, and let Google Cloud services or your own code use them to encrypt, decrypt, sign or verify, with every administrative change logged.

    BasicWhat is CMEK?

    Customer-managed encryption keys. By default Google encrypts your data at rest with keys it manages. With CMEK a service such as Cloud Storage or BigQuery encrypts under a Cloud KMS key that you own, so you control its rotation, access and the ability to disable it.

    BasicWhy can’t I delete a key ring or a key?

    Cloud KMS doesn’t support deleting key rings or keys. Google gives the reason as preventing resource name collisions, so a name always points to the key material it was created with. You can disable a key and destroy its versions, but the key ring and key names remain in the project, so pick them with care.

    IntermediateWhat are the protection levels?

    Software keys are processed in software and cost the least. HSM keys are created and used in hardware security modules that Google runs. External keys stay in a key manager outside Google, reached through Cloud EKM, which gives control of the key at the cost of availability that depends on that manager. The level is chosen when you create the key.

    IntermediateHow does Cloud KMS separate duties?

    The admin role can create, configure and destroy keys but can’t encrypt or decrypt with them. Encrypter, decrypter and signer roles allow use without management. So the people who manage keys can’t read the data, provided you give the roles to different groups and avoid broad grants.

    IntermediateWhat does rotation do to existing data?

    Rotation makes a new primary version for new encryption. Data encrypted under older versions stays readable because those versions remain enabled, and Cloud KMS picks the right version when decrypting. Re-encrypting old data under the new version is a separate task.

    AdvancedHow would you roll out CMEK across an organisation?

    Create a key project, set up Autokey on folders so teams get keys on demand in a standard pattern, and enforce the use with the organisation policy constraints for CMEK. Start in audit mode, map services to the key patterns, grant service agents only on the keys they need, and measure with Asset Inventory and Security Command Center.

    AdvancedWhat are the trade-offs of Cloud EKM?

    You keep key material outside Google and can revoke access at the source, and you can add Key Access Justifications to see why Google systems requested access. In return, each operation depends on the external manager’s availability and latency, features may be limited, and you run and pay for that manager as well.

    AdvancedHow do you protect against destroying a key version by mistake?

    Keep the default 30-day destruction delay or longer, restrict the destroy permission to a few people, alert on destroy calls from Admin Activity logs, disable a version before you destroy it and watch for failures, and for critical data keep a recoverable copy such as imported key material that you hold safely.

    AdvancedHow would you handle quotas for a high-volume service?

    Use envelope encryption with cached data keys so cryptographic calls stay low, keep software keys for volume where policy allows, since CMEK integrations on software keys aren’t quota-limited, plan HSM and external quotas in advance, retry with backoff, and request increases before a launch rather than during it.

    Similar or alternative services on other clouds

    CapabilityAWSAzureGoogle Cloud
    ServiceAWS KMSAzure Key Vault and Managed HSMCloud KMS
    Holds secrets and certificates tooNo: Secrets Manager and ACMYes, in the same vaultNo: Secret Manager and Certificate Manager
    Key containersFlat, with aliasesVaultsKey rings, keys and versions
    Hardware protectionHSMs in the service, CloudHSM storesPremium vaults or Managed HSMSoftware, HSM or external, chosen per key
    Access modelKey policy, IAM and grantsAzure RBAC, or access policies on older vaultsIAM roles; the admin role can’t use the key
    RotationAutomatic, 90 to 2,560 days, or on demandRotation policy per keyRotation period creates a new primary version
    DeletionWaiting period of 7 to 30 daysSoft delete and purge protectionVersions scheduled for destruction; key rings and keys stay
    Billing shapeAbout $1 per key a month plus requestsMostly per operation, plus HSM feesPer key version a month by level, plus operations

    Keys protect data in Cloud Storage, Cloud SQL and BigQuery, and disks on Compute Engine. For passwords and API keys use Secret Manager, which is a separate service.

    Did you find this article helpful?

    Your answer helps us improve this page for the next reader.

    Sources and further reading

    CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.