Skip to content
Learni
View all tutorials
Google Cloud

How to Set Up and Use Google Cloud KMS in 2026

Lire en français

Introduction

Google Cloud Key Management Service (KMS) is a managed service for creating, managing, and using cryptographic keys for encryption. In 2026, with rising regulations like GDPR and increasing cyber threats, KMS is essential for securing data at rest and in transit without handling the underlying infrastructure.

Think of your API secrets or customer data like a vault: KMS provides the master key. Unlike local libraries like Node.js crypto, KMS offers FIPS 140-2 certified Hardware Security Modules (HSMs), automatic key rotation, and auditing via Cloud Audit Logs. This beginner tutorial guides you step by step: CLI setup for testing, resource creation, encryption/decryption, and Node.js integration. By the end, you'll bookmark this guide for your production projects. Ready to lock down your data?

Prerequisites

  • A free Google Cloud account (console.cloud.google.com) with billing enabled.
  • gcloud CLI tools installed (cloud.google.com/sdk/docs/install).
  • Node.js 20+ and npm (nodejs.org).
  • Basic command line and JavaScript knowledge.
  • Create an empty GCP project named kms-tutorial-2026.

Install and Authenticate gcloud CLI

terminal
curl https://sdk.cloud.google.com | bash
exec -l $SHELL
gcloud init
# Suivez les invites : sélectionnez kms-tutorial-2026, authentifiez via navigateur
gcloud auth login
# Notez la sortie : votre projet est prêt

This script downloads and initializes the gcloud CLI. Authentication links your local account to the GCP project. Pitfall: On Windows, use the MSI installer; verify with gcloud config list to confirm the project.

Verify Your Environment

Run gcloud version to confirm the installation (v450+ in 2026). Create a test bucket if needed: gsutil mb gs://kms-bucket-test/. Analogy: gcloud is your GCP remote control—without it, no access to services.

Enable KMS API and Create Keyring/Key

terminal
gcloud services enable cloudkms.googleapis.com --project=kms-tutorial-2026
gcloud kms keyrings create my-keyring --location=global --project=kms-tutorial-2026
gcloud kms keys create my-key \
  --location=global \
  --keyring=my-keyring \
  --purpose=encryption \
  --project=kms-tutorial-2026
echo "Key created successfully!"

Enables the API, creates a global keyring (key wallet), and a symmetric key for encryption. --purpose=encryption uses AES-256-GCM. Pitfall: Location must match (global for beginner simplicity).

Encrypt and Decrypt via CLI

terminal
echo -n "My super confidential secret" | gcloud kms encrypt \
  --plaintext-file=- \
  --ciphertext-file=secret.enc \
  --key=my-key \
  --keyring=my-keyring \
  --location=global \
  --project=kms-tutorial-2026

cat secret.enc | gcloud kms decrypt \
  --ciphertext-file=- \
  --plaintext-file=secret.dec \
  --key=my-key \
  --keyring=my-keyring \
  --location=global \
  --project=kms-tutorial-2026

cat secret.dec  # Should display: My super confidential secret

Encrypts plaintext to binary (.enc) and decrypts back to clear text. Use --plaintext-file=- for stdin. Pitfall: Don't forget echo -n (no newline), and ensure roles/cloudkms.cryptoKeyEncrypterDecrypter permissions.

Transition to App Integration

The CLI proves the concept. Now let's move to Node.js for a real app. Download a service account key: IAM > Service Accounts > Create > kms-user@kms-tutorial-2026.iam.gserviceaccount.com, role Cloud KMS CryptoKey Encrypter/Decrypter, JSON key file. Set export GOOGLE_APPLICATION_CREDENTIALS=./service-account.json.

Initialize Node.js Project and Install SDK

terminal
mkdir kms-node-app && cd kms-node-app
npm init -y
npm install @google-cloud/kms
npm install --save-dev typescript @types/node ts-node

Creates a Node project with the official KMS client. TypeScript for robustness. Pitfall: SDK v5+ in 2026 supports native async/await; ts-node runs without building.

Complete TypeScript Script: Symmetric Encryption

kms-example.ts
import {KeyManagementServiceClient} from '@google-cloud/kms';

const client = new KeyManagementServiceClient();
const projectId = 'kms-tutorial-2026';
const locationId = 'global';
const keyRingId = 'my-keyring';
const keyId = 'my-key';
const name = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function encrypt(plaintext: string) {
  const [result] = await client.encrypt({name, plaintext: Buffer.from(plaintext)});
  console.log('Encrypted:', result.ciphertext!.toString('base64'));
  return result.ciphertext;
}

async function decrypt(ciphertext: Buffer) {
  const [result] = await client.decrypt({name, ciphertext});
  console.log('Decrypted:', result.plaintext!.toString());
}

(async () => {
  const secret = 'My Node.js secret';
  const encrypted = await encrypt(secret);
  await decrypt(encrypted);
})();

Standalone script for symmetric encryption with AES-256, Buffer/base64 handling. cryptoKeyPath builds the unique ID. Pitfall: Use Buffer for binary data; add try/catch in production for PERMISSION_DENIED errors.

TypeScript Configuration

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist"
  },
  "ts-node": {
    "esm": true
  }
}

tsconfig for modern ES modules. NodeNext avoids CJS/ESM pitfalls. Run with npx ts-node --esm kms-example.ts. Pitfall: Without esm: true, import errors occur.

Advanced Example: Key Rotation

terminal
gcloud kms keys versions create 2 \
  --key=my-key \
  --keyring=my-keyring \
  --location=global \
  --project=kms-tutorial-2026

gcloud kms keys versions use 2 \
  --key=my-key \
  --keyring=my-keyring \
  --location=global \
  --project=kms-tutorial-2026

gcloud kms keys versions list --key=my-key --keyring=my-keyring --location=global --project=kms-tutorial-2026

Creates version 2 and makes it primary for zero-downtime rotation. List versions for auditing. Pitfall: Use console for scheduled auto-rotation in production.

Best Practices

  • Minimal IAM Roles: Use roles/cloudkms.cryptoKeyEncrypterDecrypter instead of Owner.
  • Automatic Rotation: Enable in console (yearly for compliance).
  • Specific Locations: Prefer europe-west1 over global for data residency.
  • Audit Logs: Enable to track all access (free).
  • Service Accounts: Never use user keys in production; use Workload Identity.

Common Errors to Avoid

  • Location Mismatch: Keyring and key must share the same --location.
  • Missing Permissions: Check with gcloud projects get-iam-policy.
  • Plaintext with Newline: Use echo -n or Buffer.from without \n.
  • Asymmetric Key for Encrypt: --purpose=encryption is symmetric; asymmetric for signing.

Next Steps

Master Envelope Encryption for large volumes. Explore Customer Managed Encryption Keys (CMEK) with Cloud Storage.

Check out our certified Google Cloud training: from Associate Cloud Engineer to Professional Security. Official docs: cloud.google.com/kms/docs. Integrate with Secret Manager for dynamic secrets.