This page describes how to use a manually-createdCloud Key Management Serviceencryption
key with Cloud Storage, including setting default keys on buckets and adding
keys to individual objects. A Cloud KMS encryption key is acustomer-managed encryption key(CMEK). Such keys are created and managed
through Cloud KMS and stored as software keys, in anHSM cluster,
orexternally.
Whether you plan to use new or existing key rings and keys, you should
havecloudkms.cryptoKeys.setIamPolicypermission for the keys
that you will use for encryption.
This permission allows you to give Cloud Storage service agents
access to Cloud KMS keys.
The above permissions are contained in theCloud KMS Adminrole.
The key ring must be in the same location as the data you intend to encrypt,
but it can be in a different project. For available Cloud KMS
locations, seeCloud KMS locations.
Have sufficient permission to work with objects in your
Cloud Storage bucket:
If you own the project that contains the bucket, you most likely
have the necessary permission.
If you use IAM, you should havestorage.objects.createpermissionto write objects to the bucket andstorage.objects.getpermission to
read objects from the bucket. SeeUsing IAM Permissionsfor
instructions on how to get a role, such asStorage Object Adminthat has these permissions.
If you use ACLs, you should have bucket-scopedWRITERpermissionto
write objects to the bucket and object-scopedREADERpermission to
read objects from the bucket. SeeSetting ACLsfor instructions on
how to do this.
Get the email address of the service agentassociated with the project
that contains your Cloud Storage bucket. By performing this step,
you automatically create the service agent if it doesn't currently exist.
Assign a Cloud KMS key to a service agent
In order to use CMEKs, grant the Cloud Storage service agent associated
with your bucket the permission to use your Cloud KMS key for
encrypting and decrypting:
Console
In the Google Cloud console, go to theKey managementpage.
Click the name of the key ring that contains the key you want to use.
Select the checkbox for the desired key.
ThePermissionstab in the right window pane becomes available.
In theAdd principalsdialog, specify the email address of the
Cloud Storage service agent you are granting access.
In theSelect a roledrop down, selectCloud KMS CryptoKey
Encrypter/Decrypter.
ClickAdd.
To learn how to get detailed error information about failed Cloud Storage
operations in the Google Cloud console, seeTroubleshooting.
Command line
Use thegcloud storage service-agentcommand with the--authorize-cmekflag to give the service agent associated with your
bucket permission to encrypt and decrypt objects using your
Cloud KMS key:
usingGoogle.Cloud.Iam.V1;usingGoogle.Cloud.Kms.V1;publicclassIamAddMemberSample{publicPolicyIamAddMember(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringmember="user:foo@example.com"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the resource name.CryptoKeyNameresourceName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// var resourceName = new KeyRingName(projectId, locationId, keyRingId);// Get the current IAM policy.Policypolicy=client.IAMPolicyClient.GetIamPolicy(newGetIamPolicyRequest{ResourceAsResourceName=resourceName});// Add the member to the policy.policy.AddRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter",member);// Save the updated IAM policy.Policyresult=client.IAMPolicyClient.SetIamPolicy(newSetIamPolicyRequest{ResourceAsResourceName=resourceName,Policy=policy});// Return the resulting policy.returnresult;}}
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1")// iamAddMember adds a new IAM member to the Cloud KMS keyfunciamAddMember(wio.Writer,name,memberstring)error{// NOTE: The resource name can be either a key or a key ring. If IAM// permissions are granted on the key ring, the permissions apply to all keys// in the key ring.//// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// member := "user:foo@example.com"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Get the current IAM policy.handle:=client.ResourceIAM(name)policy,err:=handle.Policy(ctx)iferr!=nil{returnfmt.Errorf("failed to get IAM policy: %w",err)}// Grant the member permissions. This example grants permission to use the key// to encrypt data.policy.Add(member,"roles/cloudkms.cryptoKeyEncrypterDecrypter")iferr:=handle.SetPolicy(ctx,policy);err!=nil{returnfmt.Errorf("failed to save policy: %w",err)}fmt.Fprintf(w,"Updated IAM policy for %s\n",name)returnnil}
importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassIamAddMember{publicvoidiamAddMember()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";Stringmember="user:foo@example.com";iamAddMember(projectId,locationId,keyRingId,keyId,member);}// Add the given IAM member to the key.publicvoidiamAddMember(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,Stringmember)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the key version name from the project, location, key ring, key,// and key version.CryptoKeyNameresourceName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);// Get the current policy.Policypolicy=client.getIamPolicy(resourceName);// Create a new IAM binding for the member and role.Bindingbinding=Binding.newBuilder().setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter").addMembers(member).build();// Add the binding to the policy.PolicynewPolicy=policy.toBuilder().addBindings(binding).build();client.setIamPolicy(resourceName,newPolicy);System.out.printf("Updated IAM policy for %s%n",resourceName.toString());}}}
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const keyId = 'my-key';// const member = 'user:foo@example.com';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the resource nameconstresourceName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);asyncfunctioniamAddMember(){// Get the current IAM policy.const[policy]=awaitclient.getIamPolicy({resource:resourceName,});// Add the member to the policy.policy.bindings.push({role:'roles/cloudkms.cryptoKeyEncrypterDecrypter',members:[member],});// Save the updated policy.const[updatedPolicy]=awaitclient.setIamPolicy({resource:resourceName,policy:policy,});console.log('Updated policy');returnupdatedPolicy;}returniamAddMember();
use Google\Cloud\Iam\V1\Binding;use Google\Cloud\Iam\V1\GetIamPolicyRequest;use Google\Cloud\Iam\V1\SetIamPolicyRequest;use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;function iam_add_member(string $projectId = 'my-project',string $locationId = 'us-east1',string $keyRingId = 'my-key-ring',string $keyId = 'my-key',string $member = 'user:foo@example.com') {// Create the Cloud KMS client.$client = new KeyManagementServiceClient();// Build the resource name.$resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);// The resource name could also be a key ring.// $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);// Get the current IAM policy.$getIamPolicyRequest = (new GetIamPolicyRequest())->setResource($resourceName);$policy = $client->getIamPolicy($getIamPolicyRequest);// Add the member to the policy.$bindings = $policy->getBindings();$bindings[] = (new Binding())->setRole('roles/cloudkms.cryptoKeyEncrypterDecrypter')->setMembers([$member]);$policy->setBindings($bindings);// Save the updated IAM policy.$setIamPolicyRequest = (new SetIamPolicyRequest())->setResource($resourceName)->setPolicy($policy);$updatedPolicy = $client->setIamPolicy($setIamPolicyRequest);printf('Added %s' . PHP_EOL, $member);return $updatedPolicy;}
fromgoogle.cloudimportkmsfromgoogle.iam.v1importpolicy_pb2asiam_policydefiam_add_member(project_id:str,location_id:str,key_ring_id:str,key_id:str,member:str)->iam_policy.Policy:"""Add an IAM member to a resource.Args:project_id (string): Google Cloud project ID (e.g. 'my-project').location_id (string): Cloud KMS location (e.g. 'us-east1').key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').key_id (string): ID of the key to use (e.g. 'my-key').member (string): Member to add (e.g. 'user:foo@example.com')Returns:Policy: Updated Cloud IAM policy."""# Create the client.client=kms.KeyManagementServiceClient()# Build the resource name.resource_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# The resource name could also be a key ring.# resource_name = client.key_ring_path(project_id, location_id, key_ring_id);# Get the current policy.policy=client.get_iam_policy(request={"resource":resource_name})# Add the member to the policy.policy.bindings.add(role="roles/cloudkms.cryptoKeyEncrypterDecrypter",members=[member])# Save the updated IAM policy.request={"resource":resource_name,"policy":policy}updated_policy=client.set_iam_policy(request=request)print(f"Added{member}to{resource_name}")returnupdated_policy
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# key_id = "my-key"# member = "user:foo@example.com"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the resource name.resource_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# The resource name could also be a key ring.# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id# Create the IAM client.iam_client=Google::Cloud::Kms::V1::IAMPolicy::Client.new# Get the current IAM policy.policy=iam_client.get_iam_policyresource:resource_name# Add the member to the policy.policy.bindings<<Google::Iam::V1::Binding.new(members:[member],role:"roles/cloudkms.cryptoKeyEncrypterDecrypter")# Save the updated policy.updated_policy=iam_client.set_iam_policyresource:resource_name,policy:policyputs"Added#{member}"
WhereSERVICE_AGENT_EMAIL_ADDRESSis the
email address associated with your service agent. For example,service-7550275089395@gs-project-accounts.iam.gserviceaccount.com.
In the list of buckets, click the name of the desired bucket.
In theBucket detailspage, click theConfigurationtab.
Click thePencil iconassociated with theEncryption typeentry.
Set or remove the default Cloud KMS key for the bucket.
If the bucket isn't currently using a Cloud KMS key, select
theCustomer-managed keyradio button, then select one of the
available keys in the associated drop-down menu.
If the bucket currently uses a Cloud KMS key, change the
Cloud KMS key in the drop-down menu, or remove the
Cloud KMS key by selecting theGoogle-managed encryption keyradio button.
ClickSave.
To learn how to get detailed error information about failed Cloud Storage
operations in the Google Cloud console, seeTroubleshooting.
The following sample sets a default customer-managed encryption key on a bucket:
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&key_name){StatusOr<gcs::BucketMetadata>updated=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetEncryption(gcs::BucketEncryption{key_name}));if(!updated)throwstd::move(updated).status();if(!updated->has_encryption()){std::cerr<<"The change to set the encryption attribute on bucket "<<updated->name()<<" was successful, but the encryption is not set."<<"This is unexpected, maybe a concurrent change?\n";return;}std::cout<<"Successfully set default KMS key on bucket "<<updated->name()<<" to "<<updated->encryption().default_kms_key_name<<"."<<"\nFull metadata: "<<*updated<<"\n";}
The following sample removes the default customer-managed encryption key from a bucket:
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>updated=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().ResetEncryption());if(!updated)throwstd::move(updated).status();std::cout<<"Successfully removed default KMS key on bucket "<<updated->name()<<"\n";}
The following sample sets a default customer-managed encryption key on a bucket:
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassEnableDefaultKMSKeySample{publicBucketEnableDefaultKMSKey(stringprojectId="your-project-id",stringbucketName="your-unique-bucket-name",stringkeyLocation="us-west1",stringkmsKeyRing="kms-key-ring",stringkmsKeyName="key-name"){// KMS Key identifier of an already created KMS key.// If you use the Google.Cloud.Kms.V1 library, you can construct these names using helper class CryptoKeyName.// var fullKeyName = new CryptoKeyName(projectId, keyLocation, kmsKeyRing, kmsKeyName).ToString();stringkeyPrefix=$"projects/{projectId}/locations/{keyLocation}";stringfullKeyringName=$"{keyPrefix}/keyRings/{kmsKeyRing}";stringfullKeyName=$"{fullKeyringName}/cryptoKeys/{kmsKeyName}";varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{Projection=Projection.Full});bucket.Encryption=newBucket.EncryptionData{DefaultKmsKeyName=fullKeyName};varupdatedBucket=storage.UpdateBucket(bucket);Console.WriteLine($"Default KMS key for {bucketName} was set to {kmsKeyName}.");returnupdatedBucket;}}
The following sample removes the default customer-managed encryption key from a bucket:
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassBucketDeleteDefaultKmsKeySample{publicBucketBucketDeleteDefaultKmsKey(stringbucketName="your-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);if(bucket.Encryption==null){Console.WriteLine("No default kms key to remove");}else{bucket.Encryption.DefaultKmsKeyName=null;bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Default KMS key was removed from {bucketName}. ");}returnbucket;}}
The following sample sets a default customer-managed encryption key on a bucket:
import("context""fmt""io""time""cloud.google.com/go/storage")// setBucketDefaultKMSKey sets the Cloud KMS encryption key for the bucket.funcsetBucketDefaultKMSKey(wio.Writer,bucketName,keyNamestring)error{// bucketName := "bucket-name"// keyName := "key"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{Encryption:&storage.BucketEncryption{DefaultKMSKeyName:keyName},}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Default KMS Key Name: %v",bucketAttrsToUpdate.Encryption.DefaultKMSKeyName)returnnil}
The following sample removes the default customer-managed encryption key from a bucket:
import("context""fmt""io""time""cloud.google.com/go/storage")// removeBucketDefaultKMSKey removes any default Cloud KMS key set on a bucket.funcremoveBucketDefaultKMSKey(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{Encryption:&storage.BucketEncryption{},}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Default KMS key was removed from: %v",bucketName)returnnil}
The following sample sets a default customer-managed encryption key on a bucket:
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.Storage.BucketTargetOption;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassSetBucketDefaultKmsKey{publicstaticvoidsetBucketDefaultKmsKey(StringprojectId,StringbucketName,StringkmsKeyName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The name of the KMS key to use as a default// String kmsKeyName =// "projects/your-project-id/locations/us/keyRings/my_key_ring/cryptoKeys/my_key"Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// first look up the bucket, so we will have its metagenerationBucketbucket=storage.get(bucketName);Bucketupdated=storage.update(bucket.toBuilder().setDefaultKmsKeyName(kmsKeyName).build(),BucketTargetOption.metagenerationMatch());System.out.println("KMS Key "+updated.getDefaultKmsKeyName()+"was set to default for bucket "+bucketName);}}
The following sample removes the default customer-managed encryption key from a bucket:
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.Storage.BucketTargetOption;importcom.google.cloud.storage.StorageOptions;publicclassRemoveBucketDefaultKmsKey{publicstaticvoidremoveBucketDefaultKmsKey(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// first look up the bucket, so we will have its metagenerationBucketbucket=storage.get(bucketName);storage.update(bucket.toBuilder().setDefaultKmsKeyName(null).build(),BucketTargetOption.metagenerationMatch());System.out.println("Default KMS key was removed from "+bucketName);}}
The following sample sets a default customer-managed encryption key on a bucket:
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The name of the KMS-key to use as a default// const defaultKmsKeyName = 'my-key';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionenableDefaultKMSKey(){awaitstorage.bucket(bucketName).setMetadata({encryption:{defaultKmsKeyName,},});console.log(`Default KMS key for${bucketName}was set to${defaultKmsKeyName}.`);}enableDefaultKMSKey().catch(console.error);
The following sample removes the default customer-managed encryption key from a bucket:
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionremoveDefaultKMSKey(){awaitstorage.bucket(bucketName).setMetadata({encryption:{defaultKmsKeyName:null,},});console.log(`Default KMS key was removed from${bucketName}`);}removeDefaultKMSKey().catch(console.error);
The following sample sets a default customer-managed encryption key on a bucket:
use Google\Cloud\Storage\StorageClient;/*** Enable a bucket's requesterpays metadata.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')* @param string $kmsKeyName The KMS key to use as the default KMS key.* Key names are provided in the following format:* `projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>`.*/function enable_default_kms_key(string $bucketName, string $kmsKeyName): void{$storage = new StorageClient();$bucket = $storage->bucket($bucketName);$bucket->update(['encryption' => ['defaultKmsKeyName' => $kmsKeyName]]);printf('Default KMS key for %s was set to %s' . PHP_EOL,$bucketName,$bucket->info()['encryption']['defaultKmsKeyName']);}
The following sample removes the default customer-managed encryption key from a bucket:
use Google\Cloud\Storage\StorageClient;/*** Delete the default KMS key on the given bucket.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')*/function bucket_delete_default_kms_key(string $bucketName): void{$storage = new StorageClient();$bucket = $storage->bucket($bucketName);$objects = $bucket->objects(['encryption' => ['defaultKmsKeyName' => null,]]);printf('Default KMS key was removed from %s', $bucketName);}
The following sample sets a default customer-managed encryption key on a bucket:
fromgoogle.cloudimportstoragedefenable_default_kms_key(bucket_name,kms_key_name):"""Sets a bucket's default KMS key."""# bucket_name = "your-bucket-name"# kms_key_name = "projects/PROJ/locations/LOC/keyRings/RING/cryptoKey/KEY"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.default_kms_key_name=kms_key_namebucket.patch()print("Set default KMS key for bucket{}to{}.".format(bucket.name,bucket.default_kms_key_name))
The following sample removes the default customer-managed encryption key from a bucket:
fromgoogle.cloudimportstoragedefbucket_delete_default_kms_key(bucket_name):"""Delete a default KMS key of bucket"""# bucket_name = "your-bucket-name"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.default_kms_key_name=Nonebucket.patch()print(f"Default KMS key was removed from{bucket.name}")returnbucket
The following sample sets a default customer-managed encryption key on a bucket:
defset_bucket_default_kms_keybucket_name:,default_kms_key:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The name of the KMS key to manage this object with# default_kms_key = "projects/your-project-id/locations/global/keyRings/your-key-ring/cryptoKeys/your-key"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.default_kms_key=default_kms_keyputs"Default KMS key for#{bucket.name}was set to#{bucket.default_kms_key}"end
The following sample removes the default customer-managed encryption key from a bucket:
defbucket_delete_default_kms_keybucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.default_kms_key=nilputs"Default KMS key was removed from#{bucket_name}"end
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>metadata=client.GetBucketMetadata(bucket_name);if(!metadata)throwstd::move(metadata).status();if(!metadata->has_encryption()){std::cout<<"The bucket "<<metadata->name()<<" does not have a default KMS key set.\n";return;}std::cout<<"The default KMS key for bucket "<<metadata->name()<<" is: "<<metadata->encryption().default_kms_key_name<<"\n";}
To view the default KMS key, follow the instructions for displaying a bucket's metadata and look for
the default KMS key field in the response.
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.Map;publicclassGetBucketMetadata{publicstaticvoidgetBucketMetadata(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAMEBucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.values()));// Print bucket metadataSystem.out.println("BucketName: "+bucket.getName());System.out.println("DefaultEventBasedHold: "+bucket.getDefaultEventBasedHold());System.out.println("DefaultKmsKeyName: "+bucket.getDefaultKmsKeyName());System.out.println("Id: "+bucket.getGeneratedId());System.out.println("IndexPage: "+bucket.getIndexPage());System.out.println("Location: "+bucket.getLocation());System.out.println("LocationType: "+bucket.getLocationType());System.out.println("Metageneration: "+bucket.getMetageneration());System.out.println("NotFoundPage: "+bucket.getNotFoundPage());System.out.println("RetentionEffectiveTime: "+bucket.getRetentionEffectiveTime());System.out.println("RetentionPeriod: "+bucket.getRetentionPeriod());System.out.println("RetentionPolicyIsLocked: "+bucket.retentionPolicyIsLocked());System.out.println("RequesterPays: "+bucket.requesterPays());System.out.println("SelfLink: "+bucket.getSelfLink());System.out.println("StorageClass: "+bucket.getStorageClass().name());System.out.println("TimeCreated: "+bucket.getCreateTime());System.out.println("VersioningEnabled: "+bucket.versioningEnabled());System.out.println("ObjectRetention: "+bucket.getObjectRetention());if(bucket.getLabels()!=null){System.out.println("\n\n\nLabels:");for(Map.Entry<String,String>label:bucket.getLabels().entrySet()){System.out.println(label.getKey()+"="+label.getValue());}}if(bucket.getLifecycleRules()!=null){System.out.println("\n\n\nLifecycle Rules:");for(BucketInfo.LifecycleRulerule:bucket.getLifecycleRules()){System.out.println(rule);}}}}
To view the default KMS key, follow the instructions for displaying a bucket's metadata and look for
the default KMS key field in the response.
// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetBucketMetadata(){/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Get Bucket Metadataconst[metadata]=awaitstorage.bucket(bucketName).getMetadata();console.log(JSON.stringify(metadata,null,2));}
To view the default KMS key, follow the instructions for displaying a bucket's metadata and look for
the default KMS key field in the response.
use Google\Cloud\Storage\StorageClient;/*** Get bucket metadata.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')*/function get_bucket_metadata(string $bucketName): void{$storage = new StorageClient();$bucket = $storage->bucket($bucketName);$info = $bucket->info();printf('Bucket Metadata: %s' . PHP_EOL, print_r($info, true));}
You can encrypt an individual object with a Cloud KMS key. This is
useful if you want to use a different key from the default key set on the
bucket, or if you don't have a default key set on the bucket. The name of the
key resource used to encrypt the object is stored in the object's metadata.
Console
The Google Cloud console cannot be used to specify Cloud KMS keys
on a per-object basis. Use the gcloud CLI or the client
libraries instead.
SOURCE_DATAis the source location of the data
you're encrypting. This can be any source location supported by thecpcommand. For examplegs://my-bucket/pets/old-dog.png.
BUCKET_NAMEis the name of the destination
bucket for this copy command. For example,my-bucket.
OBJECT_NAMEis the name of the final,
encrypted object. For example,pets/new-dog.png.
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::stringconst&kms_key_name){gcs::ObjectWriteStreamstream=client.WriteObject(bucket_name,object_name,gcs::KmsKeyName(kms_key_name));// Line numbers start at 1.for(intlineno=1;lineno<=10;++lineno){stream<<lineno<<": placeholder text for CMEK example.\n";}stream.Close();StatusOr<gcs::ObjectMetadata>metadata=std::move(stream).metadata();if(!metadata)throwstd::move(metadata).status();std::cout<<"Successfully wrote to object "<<metadata->name()<<" its size is: "<<metadata->size()<<"\nFull metadata: "<<*metadata<<"\n";}
usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.IO;publicclassUploadFileWithKmsKeySample{publicvoidUploadFileWithKmsKey(stringprojectId="your-project-id",stringbucketName="your-unique-bucket-name",stringkeyLocation="us-west1",stringkmsKeyRing="kms-key-ring",stringkmsKeyName="key-name",stringlocalPath="my-local-path/my-file-name",stringobjectName="my-file-name"){// KMS Key identifier of an already created KMS key.// If you use the Google.Cloud.Kms.V1 library, you can construct these names using helper class CryptoKeyName.// var fullKeyName = new CryptoKeyName(projectId, keyLocation, kmsKeyRing, kmsKeyName).ToString();stringkeyPrefix=$"projects/{projectId}/locations/{keyLocation}";stringfullKeyringName=$"{keyPrefix}/keyRings/{kmsKeyRing}";stringfullKeyName=$"{fullKeyringName}/cryptoKeys/{kmsKeyName}";varstorage=StorageClient.Create();usingvarfileStream=File.OpenRead(localPath);storage.UploadObject(bucketName,objectName,null,fileStream,newUploadObjectOptions{KmsKeyName=fullKeyName});Console.WriteLine($"Uploaded {objectName}.");}}
import("context""fmt""io""time""cloud.google.com/go/storage")// uploadWithKMSKey writes an object using Cloud KMS encryption.funcuploadWithKMSKey(wio.Writer,bucket,object,keyNamestring)error{// bucket := "bucket-name"// object := "object-name"// keyName := "projects/projectId/locations/global/keyRings/keyRingID/cryptoKeys/cryptoKeyID"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*50)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload is aborted if the// object's generation number does not match your precondition.// For an object that does not yet exist, set the DoesNotExist precondition.o=o.If(storage.Conditions{DoesNotExist:true})// If the live object already exists in your bucket, set instead a// generation-match precondition using the live object's generation number.// attrs, err := o.Attrs(ctx)// if err != nil {// return fmt.Errorf("object.Attrs: %w", err)// }// o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})// Encrypt the object's contents.wc:=o.NewWriter(ctx)wc.KMSKeyName=keyNameif_,err:=wc.Write([]byte("top secret"));err!=nil{returnfmt.Errorf("Writer.Write: %w",err)}iferr:=wc.Close();err!=nil{returnfmt.Errorf("Writer.Close: %w",err)}fmt.Fprintf(w,"Uploaded blob %v with KMS key.\n",object)returnnil}
import staticjava.nio.charset.StandardCharsets.UTF_8;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.BlobInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassUploadKmsEncryptedObject{publicstaticvoiduploadKmsEncryptedObject(StringprojectId,StringbucketName,StringobjectName,StringkmsKeyName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";// The name of the KMS key to encrypt with// String kmsKeyName = "projects/my-project/locations/us/keyRings/my_key_ring/cryptoKeys/my_key"Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();byte[]data="Hello, World!".getBytes(UTF_8);BlobIdblobId=BlobId.of(bucketName,objectName);BlobInfoblobInfo=BlobInfo.newBuilder(blobId).setContentType("text/plain").build();// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request returns a 412 error if the// preconditions are not met.Storage.BlobTargetOptionprecondition;if(storage.get(bucketName,objectName)==null){// For a target object that does not yet exist, set the DoesNotExist precondition.// This will cause the request to fail if the object is created before the request runs.precondition=Storage.BlobTargetOption.doesNotExist();}else{// If the destination already exists in your bucket, instead set a generation-match// precondition. This will cause the request to fail if the existing object's generation// changes before the request runs.precondition=Storage.BlobTargetOption.generationMatch(storage.get(bucketName,objectName).getGeneration());}storage.create(blobInfo,data,Storage.BlobTargetOption.kmsKeyName(kmsKeyName),precondition);System.out.println("Uploaded object "+objectName+" in bucket "+bucketName+" encrypted with "+kmsKeyName);}}
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The path to your file to upload// const filePath = 'path/to/your/file';// The name of the KMS-key// const kmsKeyName = 'my-key';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionuploadFileWithKmsKey(){constoptions={kmsKeyName,// Optional:// Set a generation-match precondition to avoid potential race conditions// and data corruptions. The request to upload is aborted if the object's// generation number does not match your precondition. For a destination// object that does not yet exist, set the ifGenerationMatch precondition to 0// If the destination object already exists in your bucket, set instead a// generation-match precondition using its generation number.preconditionOpts:{ifGenerationMatch:generationMatchPrecondition},};awaitstorage.bucket(bucketName).upload(filePath,options);console.log(`${filePath}uploaded to${bucketName}using${kmsKeyName}.`);}uploadFileWithKmsKey().catch(console.error);
use Google\Cloud\Storage\StorageClient;/*** Upload a file using KMS encryption.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')* @param string $objectName The name of your Cloud Storage object.* (e.g. 'my-object')* @param string $source The path to the file to upload.* (e.g. '/path/to/your/file')* @param string $kmsKeyName The KMS key used to encrypt objects server side.* Key names are provided in the following format:* `projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>`.*/function upload_with_kms_key(string $bucketName, string $objectName, string $source, string $kmsKeyName): void{$storage = new StorageClient();if (!$file = fopen($source, 'r')) {throw new \InvalidArgumentException('Unable to open file for reading');}$bucket = $storage->bucket($bucketName);$object = $bucket->upload($file, ['name' => $objectName,'destinationKmsKeyName' => $kmsKeyName,]);printf('Uploaded %s to gs://%s/%s using encryption key %s' . PHP_EOL,basename($source),$bucketName,$objectName,$kmsKeyName);}
fromgoogle.cloudimportstoragedefupload_blob_with_kms(bucket_name,source_file_name,destination_blob_name,kms_key_name,):"""Uploads a file to the bucket, encrypting it with the given KMS key."""# bucket_name = "your-bucket-name"# source_file_name = "local/path/to/file"# destination_blob_name = "storage-object-name"# kms_key_name = "projects/PROJ/locations/LOC/keyRings/RING/cryptoKey/KEY"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(destination_blob_name,kms_key_name=kms_key_name)# Optional: set a generation-match precondition to avoid potential race conditions# and data corruptions. The request to upload is aborted if the object's# generation number does not match your precondition. For a destination# object that does not yet exist, set the if_generation_match precondition to 0.# If the destination object already exists in your bucket, set instead a# generation-match precondition using its generation number.generation_match_precondition=0blob.upload_from_filename(source_file_name,if_generation_match=generation_match_precondition)print("File{}uploaded to{}with encryption key{}.".format(source_file_name,destination_blob_name,kms_key_name))
defupload_with_kms_keybucket_name:,local_file_path:,file_name:nil,kms_key:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The path to your file to upload# local_file_path = "/local/path/to/file.txt"# The ID of your GCS object# file_name = "your-file-name"# The name of the KMS key to manage this object with# kms_key = "projects/your-project-id/locations/global/keyRings/your-key-ring/cryptoKeys/your-key"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.create_filelocal_file_path,file_name,kms_key:kms_keyputs"Uploaded#{file.name}and encrypted service side using#{file.kms_key}"end
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::stringconst&old_csek_key_base64,std::stringconst&new_cmek_key_name){StatusOr<gcs::ObjectMetadata>metadata=client.RewriteObjectBlocking(bucket_name,object_name,bucket_name,object_name,gcs::SourceEncryptionKey::FromBase64Key(old_csek_key_base64),gcs::DestinationKmsKeyName(new_cmek_key_name));if(!metadata)throwstd::move(metadata).status();std::cout<<"Changed object "<<metadata->name()<<" in bucket "<<metadata->bucket()<<" from using CSEK to CMEK key.\nFull Metadata: "<<*metadata<<"\n";}
usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.IO;publicclassObjectCsekToCmekSample{publicvoidObjectCsekToCmek(stringprojectId="your-project-id",stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name",stringcurrrentEncryptionKey="TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=",stringkeyLocation="us-west1",stringkmsKeyRing="kms-key-ring",stringkmsKeyName="key-name"){stringkeyPrefix=$"projects/{projectId}/locations/{keyLocation}";stringfullKeyringName=$"{keyPrefix}/keyRings/{kmsKeyRing}";stringfullKeyName=$"{fullKeyringName}/cryptoKeys/{kmsKeyName}";varstorage=StorageClient.Create();usingvaroutputStream=newMemoryStream();storage.DownloadObject(bucketName,objectName,outputStream,newDownloadObjectOptions(){EncryptionKey=EncryptionKey.Create(Convert.FromBase64String(currrentEncryptionKey))});outputStream.Position=0;storage.UploadObject(bucketName,objectName,null,outputStream,newUploadObjectOptions(){KmsKeyName=fullKeyName});Console.WriteLine($"Object {objectName} in bucket {bucketName} is now managed"+$" by the KMS key ${kmsKeyName} instead of a customer-supplied encryption key");}}
import("context""fmt""io""time""cloud.google.com/go/storage")// сhangeObjectCSEKtoKMS changes the key used to encrypt an object from// a customer-supplied encryption key to a customer-managed encryption key.funcсhangeObjectCSEKToKMS(wio.WrWriterbucket,objectstring,encryptionKey[]byte,kmsKeyNamestring)error{// bucket := "bucket-name"// object := "object-name"// encryptionKey is the Base64 encoded decryption key, which should be the same// key originally used to encrypt the object.// encryptionKey := []byte("TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=")// kmsKeyName is the name of the KMS key to manage this object with.// kmsKeyName := "projects/projectId/locations/global/keyRings/keyRingID/cryptoKeys/cryptoKeyID"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=clclient.Bucket(bucket).Objectbject)// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to copy is aborted if the// object's generation number does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.CoConditionsenerationMatch:atattrs.Generation// You can't change an object's encryption key directly. Instead, you must// rewrite the object using the new key.src:=o.o.KeyncryptionKey)c:=o.o.CopierFromrc)c.DestinationKMSKeyName=kmsKeyNameif_,err:=c.Run(ctx);err!=nil{returnfmt.Errorf("Copier.Run: %w",err)}fmt.Fprintf(w,"Object %v in bucket %v is now managed by the KMS key %v instead of a customer-supplied encryption key\n",object,bucket,kmsKeyName)returnnil}
importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassChangeObjectCsekToKms{publicstaticvoidchangeObjectFromCsekToKms(StringprojectId,StringbucketName,StringobjectName,StringdecryptionKey,StringkmsKeyName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";// The Base64 encoded decryption key, which should be the same key originally used to encrypt// the object// String decryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=";// The name of the KMS key to manage this object with// String kmsKeyName =// "projects/your-project-id/locations/global/keyRings/your-key-ring/cryptoKeys/your-key";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" wasn't found in "+bucketName);return;}// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload returns a 412 error if// the object's generation number does not match your precondition.Storage.BlobSourceOptionprecondition=Storage.BlobSourceOption.generationMatch(blob.getGeneration());Storage.CopyRequestrequest=Storage.CopyRequest.newBuilder().setSource(blobId).setSourceOptions(Storage.BlobSourceOption.decryptionKey(decryptionKey),precondition).setTarget(blobId,Storage.BlobTargetOption.kmsKeyName(kmsKeyName)).build();storage.copy(request);System.out.println("Object "+objectName+" in bucket "+bucketName+" is now managed by the KMS key "+kmsKeyName+" instead of a customer-supplied encryption key");}}
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// The Base64 encoded decryption key, which should be the same key originally// used to encrypt the file// const encryptionKey = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=';// The name of the KMS key to manage this file with// const kmsKeyName = 'projects/your-project-id/locations/global/keyRings/your-key-ring/cryptoKeys/your-key';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionchangeFileCSEKToCMEK(){constrotateEncryptionKeyOptions={kmsKeyName,// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to copy is aborted if the// object's generation number does not match your precondition.preconditionOpts:{ifGenerationMatch:generationMatchPrecondition,},};console.log(rotateEncryptionKeyOptions);awaitstorage.bucket(bucketName).file(fileName,{encryptionKey:Buffer.from(encryptionKey,'base64'),}).rotateEncryptionKey({rotateEncryptionKeyOptions,});console.log(`file${fileName}in bucket${bucketName}is now managed by KMS key${kmsKeyName}instead of customer-supplied encryption key`);}changeFileCSEKToCMEK().catch(console.error);
use Google\Cloud\Storage\StorageClient;/*** Migrate an object from a Customer-Specified Encryption Key to a Customer-Managed* Encryption Key.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')* @param string $objectName The name of your Cloud Storage object.* (e.g. 'my-object')* @param string $decryptionKey The Base64 encoded decryption key, which should* (e.g. 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=')* be the same key originally used to encrypt the object.* @param string $kmsKeyName The name of the KMS key to manage this object.* Key names are provided in the following format:* `projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>`.*/function object_csek_to_cmek(string $bucketName, string $objectName, string $decryptionKey, string $kmsKeyName): void{$storage = new StorageClient();$bucket = $storage->bucket($bucketName);$object = $bucket->object($objectName, ['encryptionKey' => $decryptionKey,]);$object->rewrite($bucketName, ['destinationKmsKeyName' => $kmsKeyName,]);printf('Object %s in bucket %s is now managed by the KMS key %s instead of a customer-supplied encryption key',$objectName,$bucketName,$kmsKeyName);}
fromgoogle.cloudimportstoragedefobject_csek_to_cmek(bucket_name,blob_name,encryption_key,kms_key_name):"""Change a blob's customer-supplied encryption key to KMS key"""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"# encryption_key = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="# kms_key_name = "projects/PROJ/locations/LOC/keyRings/RING/cryptoKey/KEY"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)current_encryption_key=base64.b64decode(encryption_key)source_blob=bucket.blob(blob_name,encryption_key=current_encryption_key)destination_blob=bucket.blob(blob_name,kms_key_name=kms_key_name)generation_match_precondition=Nonetoken=None# Optional: set a generation-match precondition to avoid potential race conditions# and data corruptions. The request to rewrite is aborted if the object's# generation number does not match your precondition.source_blob.reload()# Fetch blob metadata to use in generation_match_precondition.generation_match_precondition=source_blob.generationwhileTrue:token,bytes_rewritten,total_bytes=destination_blob.rewrite(source_blob,token=token,if_generation_match=generation_match_precondition)iftokenisNone:breakprint("Blob{}in bucket{}is now managed by the KMS key{}instead of a customer-supplied encryption key".format(blob_name,bucket_name,kms_key_name))returndestination_blob
defobject_csek_to_cmekbucket_name:,file_name:,encryption_key:,kms_key_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"# The Base64 encoded encryption key, which should be the same key originally used to encrypt the object# encryption_key = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="# The name of the KMS key to manage this object with# kms_key_name = "projects/your-project-id/locations/global/keyRings/your-key-ring/cryptoKeys/your-key"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_name,encryption_key:encryption_keyfile.rotateencryption_key:encryption_key,new_kms_key:kms_key_nameputs"File#{file_name}in bucket#{bucket_name}is now managed by the KMS key#{kms_key_name}instead of a "\"customer-supplied encryption key"end
The XML API does not support rotating from a customer-supplied
encryption key to a Cloud KMS key through rewriting object. To
perform such a rotation using the XML API, you should:
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>metadata=client.GetObjectMetadata(bucket_name,object_name);if(!metadata)throwstd::move(metadata).status();std::cout<<"KMS key on object "<<metadata->name()<<" in bucket "<<metadata->bucket()<<": "<<metadata->kms_key_name()<<"\n";}
To view the KMS key associated with an object, follow the instructions for displaying an object's metadata and look for
the KMS key name field in the response.
usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetMetadataSample{publicGoogle.Apis.Storage.v1.Data.ObjectGetMetadata(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName,newGetObjectOptions{Projection=Projection.Full});Console.WriteLine($"Bucket:\t{storageObject.Bucket}");Console.WriteLine($"CacheControl:\t{storageObject.CacheControl}");Console.WriteLine($"ComponentCount:\t{storageObject.ComponentCount}");Console.WriteLine($"ContentDisposition:\t{storageObject.ContentDisposition}");Console.WriteLine($"ContentEncoding:\t{storageObject.ContentEncoding}");Console.WriteLine($"ContentLanguage:\t{storageObject.ContentLanguage}");Console.WriteLine($"ContentType:\t{storageObject.ContentType}");Console.WriteLine($"Crc32c:\t{storageObject.Crc32c}");Console.WriteLine($"ETag:\t{storageObject.ETag}");Console.WriteLine($"Generation:\t{storageObject.Generation}");Console.WriteLine($"Id:\t{storageObject.Id}");Console.WriteLine($"Kind:\t{storageObject.Kind}");Console.WriteLine($"KmsKeyName:\t{storageObject.KmsKeyName}");Console.WriteLine($"Md5Hash:\t{storageObject.Md5Hash}");Console.WriteLine($"MediaLink:\t{storageObject.MediaLink}");Console.WriteLine($"Metageneration:\t{storageObject.Metageneration}");Console.WriteLine($"Name:\t{storageObject.Name}");Console.WriteLine($"Retention:\t{storageObject.Retention}");Console.WriteLine($"Size:\t{storageObject.Size}");Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");Console.WriteLine($"Updated:\t{storageObject.Updated}");booleventBasedHold=storageObject.EventBasedHold??false;Console.WriteLine("Event-based hold enabled? {0}",eventBasedHold);booltemporaryHold=storageObject.TemporaryHold??false;Console.WriteLine("Temporary hold enabled? {0}",temporaryHold);Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");if(storageObject.Metadata!=null){Console.WriteLine("Metadata: ");foreach(varmetadatainstorageObject.Metadata){Console.WriteLine($"{metadata.Key}:\t{metadata.Value}");}}Console.WriteLine($"CustomTime:\t{storageObject.CustomTime}");returnstorageObject;}}
To view the KMS key associated with an object, follow the instructions for displaying an object's metadata and look for
the KMS key name field in the response.
import("context""fmt""io""time""cloud.google.com/go/storage")// getMetadata prints all of the object attributes.funcgetMetadata(wio.Writer,bucket,objectstring)(*storage.ObjectAttrs,error){// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)attrs,err:=o.Attrs(ctx)iferr!=nil{returnnil,fmt.Errorf("Object(%q).Attrs: %w",object,err)}fmt.Fprintf(w,"Bucket: %v\n",attrs.Bucket)fmt.Fprintf(w,"CacheControl: %v\n",attrs.CacheControl)fmt.Fprintf(w,"ContentDisposition: %v\n",attrs.ContentDisposition)fmt.Fprintf(w,"ContentEncoding: %v\n",attrs.ContentEncoding)fmt.Fprintf(w,"ContentLanguage: %v\n",attrs.ContentLanguage)fmt.Fprintf(w,"ContentType: %v\n",attrs.ContentType)fmt.Fprintf(w,"Crc32c: %v\n",attrs.CRC32C)fmt.Fprintf(w,"Generation: %v\n",attrs.Generation)fmt.Fprintf(w,"KmsKeyName: %v\n",attrs.KMSKeyName)fmt.Fprintf(w,"Md5Hash: %v\n",attrs.MD5)fmt.Fprintf(w,"MediaLink: %v\n",attrs.MediaLink)fmt.Fprintf(w,"Metageneration: %v\n",attrs.Metageneration)fmt.Fprintf(w,"Name: %v\n",attrs.Name)fmt.Fprintf(w,"Size: %v\n",attrs.Size)fmt.Fprintf(w,"StorageClass: %v\n",attrs.StorageClass)fmt.Fprintf(w,"TimeCreated: %v\n",attrs.Created)fmt.Fprintf(w,"Updated: %v\n",attrs.Updated)fmt.Fprintf(w,"Event-based hold enabled? %t\n",attrs.EventBasedHold)fmt.Fprintf(w,"Temporary hold enabled? %t\n",attrs.TemporaryHold)fmt.Fprintf(w,"Retention expiration time %v\n",attrs.RetentionExpirationTime)fmt.Fprintf(w,"Custom time %v\n",attrs.CustomTime)fmt.Fprintf(w,"Retention: %+v\n",attrs.Retention)fmt.Fprintf(w,"\n\nMetadata\n")forkey,value:=rangeattrs.Metadata{fmt.Fprintf(w,"\t%v = %v\n",key,value)}returnattrs,nil}
To view the KMS key associated with an object, follow the instructions for displaying an object's metadata and look for
the KMS key name field in the response.
importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;importjava.util.Map;publicclassGetObjectMetadata{publicstaticvoidgetObjectMetadata(StringprojectId,StringbucketName,StringblobName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Select all fields// Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROLBlobblob=storage.get(bucketName,blobName,Storage.BlobGetOption.fields(Storage.BlobField.values()));// Print blob metadataSystem.out.println("Bucket: "+blob.getBucket());System.out.println("CacheControl: "+blob.getCacheControl());System.out.println("ComponentCount: "+blob.getComponentCount());System.out.println("ContentDisposition: "+blob.getContentDisposition());System.out.println("ContentEncoding: "+blob.getContentEncoding());System.out.println("ContentLanguage: "+blob.getContentLanguage());System.out.println("ContentType: "+blob.getContentType());System.out.println("CustomTime: "+blob.getCustomTime());System.out.println("Crc32c: "+blob.getCrc32c());System.out.println("Crc32cHexString: "+blob.getCrc32cToHexString());System.out.println("ETag: "+blob.getEtag());System.out.println("Generation: "+blob.getGeneration());System.out.println("Id: "+blob.getBlobId());System.out.println("KmsKeyName: "+blob.getKmsKeyName());System.out.println("Md5Hash: "+blob.getMd5());System.out.println("Md5HexString: "+blob.getMd5ToHexString());System.out.println("MediaLink: "+blob.getMediaLink());System.out.println("Metageneration: "+blob.getMetageneration());System.out.println("Name: "+blob.getName());System.out.println("Size: "+blob.getSize());System.out.println("StorageClass: "+blob.getStorageClass());System.out.println("TimeCreated: "+newDate(blob.getCreateTime()));System.out.println("Last Metadata Update: "+newDate(blob.getUpdateTime()));System.out.println("Object Retention Policy: "+blob.getRetention());BooleantemporaryHoldIsEnabled=(blob.getTemporaryHold()!=null&&blob.getTemporaryHold());System.out.println("temporaryHold: "+(temporaryHoldIsEnabled?"enabled":"disabled"));BooleaneventBasedHoldIsEnabled=(blob.getEventBasedHold()!=null&&blob.getEventBasedHold());System.out.println("eventBasedHold: "+(eventBasedHoldIsEnabled?"enabled":"disabled"));if(blob.getRetentionExpirationTime()!=null){System.out.println("retentionExpirationTime: "+newDate(blob.getRetentionExpirationTime()));}if(blob.getMetadata()!=null){System.out.println("\n\n\nUser metadata:");for(Map.Entry<String,String>userMetadata:blob.getMetadata().entrySet()){System.out.println(userMetadata.getKey()+"="+userMetadata.getValue());}}}}
To view the KMS key associated with an object, follow the instructions for displaying an object's metadata and look for
the KMS key name field in the response.
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetMetadata(){// Gets the metadata for the fileconst[metadata]=awaitstorage.bucket(bucketName).file(fileName).getMetadata();console.log(`Bucket:${metadata.bucket}`);console.log(`CacheControl:${metadata.cacheControl}`);console.log(`ComponentCount:${metadata.componentCount}`);console.log(`ContentDisposition:${metadata.contentDisposition}`);console.log(`ContentEncoding:${metadata.contentEncoding}`);console.log(`ContentLanguage:${metadata.contentLanguage}`);console.log(`ContentType:${metadata.contentType}`);console.log(`CustomTime:${metadata.customTime}`);console.log(`Crc32c:${metadata.crc32c}`);console.log(`ETag:${metadata.etag}`);console.log(`Generation:${metadata.generation}`);console.log(`Id:${metadata.id}`);console.log(`KmsKeyName:${metadata.kmsKeyName}`);console.log(`Md5Hash:${metadata.md5Hash}`);console.log(`MediaLink:${metadata.mediaLink}`);console.log(`Metageneration:${metadata.metageneration}`);console.log(`Name:${metadata.name}`);console.log(`Size:${metadata.size}`);console.log(`StorageClass:${metadata.storageClass}`);console.log(`TimeCreated:${newDate(metadata.timeCreated)}`);console.log(`Last Metadata Update:${newDate(metadata.updated)}`);console.log(`TurboReplication:${metadata.rpo}`);console.log(`temporaryHold:${metadata.temporaryHold?'enabled':'disabled'}`);console.log(`eventBasedHold:${metadata.eventBasedHold?'enabled':'disabled'}`);if(metadata.retentionExpirationTime){console.log(`retentionExpirationTime:${newDate(metadata.retentionExpirationTime)}`);}if(metadata.metadata){console.log('\n\n\nUser metadata:');for(constkeyinmetadata.metadata){console.log(`${key}=${metadata.metadata[key]}`);}}}getMetadata().catch(console.error);
To view the KMS key associated with an object, follow the instructions for displaying an object's metadata and look for
the KMS key name field in the response.
fromgoogle.cloudimportstoragedefobject_get_kms_key(bucket_name,blob_name):"""Retrieve the KMS key of a blob"""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.get_blob(blob_name)kms_key=blob.kms_key_nameprint(f"The KMS key of a blob is{blob.kms_key_name}")returnkms_key
To view the KMS key associated with an object, follow the instructions for displaying an object's metadata and look for
the KMS key name field in the response.
defget_metadatabucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namefile=bucket.filefile_nameputs"Name:#{file.name}"puts"Bucket:#{bucket.name}"puts"Storage class:#{bucket.storage_class}"puts"ID:#{file.id}"puts"Size:#{file.size}bytes"puts"Created:#{file.created_at}"puts"Updated:#{file.updated_at}"puts"Generation:#{file.generation}"puts"Metageneration:#{file.metageneration}"puts"Etag:#{file.etag}"puts"Owners:#{file.acl.owners.join','}"puts"Crc32c:#{file.crc32c}"puts"md5_hash:#{file.md5}"puts"Cache-control:#{file.cache_control}"puts"Content-type:#{file.content_type}"puts"Content-disposition:#{file.content_disposition}"puts"Content-encoding:#{file.content_encoding}"puts"Content-language:#{file.content_language}"puts"KmsKeyName:#{file.kms_key}"puts"Event-based hold enabled?:#{file.event_based_hold?}"puts"Temporary hold enaled?:#{file.temporary_hold?}"puts"Retention Expiration:#{file.retention_expires_at}"puts"Custom Time:#{file.custom_time}"puts"Metadata:"file.metadata.eachdo|key,value|puts" -#{key}=#{value}"endend
BUCKET_NAMEis the name of the bucket
containing the encrypted object. For example,my-bucket.
OBJECT_NAMEis the URL-encoded name
of the encrypted object. For example,pets/dog.png,
URL-encoded aspets%2Fdog.png.
Decrypt an object
Decrypting an object encrypted with a Cloud KMS key is performed
automatically as long as the relevant service agent has access to the key. For
more information, seeService agents with CMEKs.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]