顧客管理の暗号鍵を使用する

概要

このページでは、バケットでデフォルトの鍵を設定する方法や個々のオブジェクトに鍵を追加するなど、Cloud Storage で Cloud Key Management Service の暗号鍵を使用する方法について説明します。Cloud KMS 暗号鍵は顧客管理の暗号鍵です。このような鍵は、Cloud KMS で作成および管理され、HSM クラスタ内または外部でソフトウェア鍵として保存されます。

始める前に

Cloud Storage でこの機能を使用する前に、以下の準備が必要です。

  1. 暗号鍵を格納するプロジェクトの Cloud KMS API を有効にする。

    API を有効にする

  2. 暗号鍵を格納するプロジェクトに対して十分な権限を持つ。

    • 鍵が保存されるプロジェクトを所有している場合は、必要な権限があると考えられます。

    • 新しい暗号キーリングと鍵を作成する予定がある場合は、cloudkms.keyRings.createcloudkms.cryptoKeys.create の権限が必要です。

    • キーリングと鍵を使用する予定がある場合は、それが新規か既存かを問わず、暗号化に使用する鍵に対する cloudkms.cryptoKeys.setIamPolicy 権限が必要です。

      この権限があると、Cloud Storage サービス エージェントに Cloud KMS 鍵へのアクセス権を付与できます。

    • 上記の権限は、Cloud KMS 管理者ロールに含まれています。

      この役割を含め、Cloud KMS の役割の取得方法については、IAM と Cloud KMS の使用をご覧ください。

  3. Cloud KMS キーリングと、キーリング内に少なくとも 1 つの鍵を持っている。

    キーリングは暗号化するデータと同じロケーションに存在する必要がありますが、別のプロジェクトに配置することもできます。指定できる Cloud KMS のロケーションについては、Cloud KMS のロケーションをご覧ください。

  4. Cloud Storage バケット内のオブジェクトを操作するための十分な権限を持つ。

    • バケットを含むプロジェクトを所有している場合は、必要な権限を持っていると考えられます。

    • IAM を使用する場合は、バケットにオブジェクトを書き込むための storage.objects.create 権限とバケットからオブジェクトを読み取るための storage.objects.get 権限が必要です。これらの権限を持つロール(ストレージ オブジェクト管理者など)を取得する手順については、IAM 権限の使用をご覧ください。

    • ACL を使用する場合は、バケットにオブジェクトを書き込むためのバケット範囲の WRITER 権限とバケットからオブジェクトを読み取るためのオブジェクト範囲の READER 権限が必要です。設定方法については、ACL の設定をご覧ください。

  5. Cloud Storage バケットを含むプロジェクトに関連付けられているサービス エージェントのメールアドレスを取得する。この手順を行うと、サービス エージェントが自動的に作成されます(存在しない場合)。

サービス エージェントに Cloud KMS 鍵を割り当てる

顧客管理の暗号鍵を使用するには、バケットに関連付けられている Cloud Storage サービス エージェントに、Cloud KMS 鍵を使用して暗号化と復号を行う権限を付与します。

コンソール

  1. Google Cloud コンソールで Cloud Key Management Service 鍵のブラウザを開きます。
    Cloud KMS 鍵のブラウザを開く
  2. 使用する鍵を含むキーリングの名前をクリックします。

  3. 使用する鍵のチェックボックスをオンにします。

    右側のウィンドウの [権限] タブが有効になります。

  4. [プリンシパルを追加] ダイアログで、アクセス権を付与する Cloud Storage サービス エージェントのメールアドレスを指定します。

  5. [ロールを選択] プルダウンで、[クラウド KMS 暗号鍵の暗号化 / 復号化] を選択します。

  6. [追加] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

gcloud storage service-agent コマンドを --authorize-cmek フラグとともに使用して、バケットに関連付けられたサービス エージェントに、Cloud KMS 鍵を使用してオブジェクトを暗号化、復号する権限を付与します。

gcloud storage service-agent --project=PROJECT_STORING_OBJECTS --authorize-cmek=KEY_RESOURCE

ここで

  • PROJECT_STORING_OBJECTS は、暗号化または復号するオブジェクトが含まれているプロジェクトの ID または番号です。例: my-pet-project
  • KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

クライアント ライブラリ

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.Kms.V1;

public class IamAddMemberSample
{
    public Policy IamAddMember(
      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 client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(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.
        Policy policy = client.IAMPolicyClient.GetIamPolicy(
            new GetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName
            });

        // Add the member to the policy.
        policy.AddRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter", member);

        // Save the updated IAM policy.
        Policy result = client.IAMPolicyClient.SetIamPolicy(
            new SetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName,
                Policy = policy
            });

        // Return the resulting policy.
        return result;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
)

// iamAddMember adds a new IAM member to the Cloud KMS key
func iamAddMember(w io.Writer, name, member string) 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)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Get the current IAM policy.
	handle := client.ResourceIAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.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")
	if err := handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %w", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class IamAddMember {

  public void iamAddMember() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String member = "user:foo@example.com";
    iamAddMember(projectId, locationId, keyRingId, keyId, member);
  }

  // Add the given IAM member to the key.
  public void iamAddMember(
      String projectId, String locationId, String keyRingId, String keyId, String member)
      throws IOException {
    // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyName resourceName = 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.
      Policy policy = client.getIamPolicy(resourceName);

      // Create a new IAM binding for the member and role.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter")
              .addMembers(member)
              .build();

      // Add the binding to the policy.
      Policy newPolicy = policy.toBuilder().addBindings(binding).build();

      client.setIamPolicy(resourceName, newPolicy);
      System.out.printf("Updated IAM policy for %s%n", resourceName.toString());
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

//
// 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the resource name
const resourceName = client.cryptoKeyPath(
  projectId,
  locationId,
  keyRingId,
  keyId
);

// The resource name could also be a key ring.
// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);

async function iamAddMember() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: resourceName,
  });

  // Add the member to the policy.
  policy.bindings.push({
    role: 'roles/cloudkms.cryptoKeyEncrypterDecrypter',
    members: [member],
  });

  // Save the updated policy.
  const [updatedPolicy] = await client.setIamPolicy({
    resource: resourceName,
    policy: policy,
  });

  console.log('Updated policy');
  return updatedPolicy;
}

return iamAddMember();

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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;
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import kms
from google.iam.v1 import policy_pb2 as iam_policy

def iam_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}")
    return updated_policy

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

# 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_path project:    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_policy resource: 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_policy resource: resource_name, policy: policy
puts "Added #{member}"

REST API

JSON API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる JSON ファイルを作成します。

    {
      "policy": {
        "bindings": {
          "role": "roles/cloudkms.cryptoKeyEncrypterDecrypter",
          "members": "serviceAccount:SERVICE_AGENT_EMAIL_ADDRESS"
        },
      }
    }

    ここで、SERVICE_AGENT_EMAIL_ADDRESS はサービス エージェントに関連付けられたメールアドレスです。例: service-7550275089395@gs-project-accounts.iam.gserviceaccount.com

  3. cURL を使用して、POST setIamPolicy リクエストで Cloud KMS API を呼び出します。

    curl -X POST --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://cloudkms.googleapis.com/v1/KEY_RESOURCE:setIamPolicy"

    ここで

    • JSON_FILE_NAME は、手順 2 で作成した JSON ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

XML API

XML API を使用して、Cloud KMS をサービス エージェントに割り当てることはできません。代わりに、gcloud CLI などの他の Cloud Storage ツールを使用してください。

デフォルトの暗号鍵を使用する

バケットのデフォルトの鍵を設定する

オブジェクトがバケットに書き込まれたときにデフォルトで使用される Cloud KMS 鍵を追加、変更、または削除するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、目的のバケットの名前をクリックします。

  3. [バケットの詳細] ページで、[構成] タブをクリックします。

  4. 暗号化タイプのエントリに関連付けられた鉛筆アイコンをクリックします。

  5. バケットのデフォルトの Cloud KMS 鍵を設定または削除します。

    1. 現在、バケットで Cloud KMS 鍵が使用されていない場合は、[顧客管理の暗号鍵] ラジオボタンを選択し、関連するプルダウン メニューで使用可能な鍵を選択します。

    2. バケットで現在 Cloud KMS 鍵が使用されている場合は、プルダウン メニューで Cloud KMS 鍵を変更するか、[Google が管理する暗号鍵] ラジオボタンを選択して Cloud KMS 鍵を削除します。

  6. [保存] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

適切なフラグを指定して、gcloud storage buckets update コマンドを使用します。

gcloud storage buckets update gs://BUCKET_NAME FLAG

ここで

  • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

  • FLAG は、バケットのデフォルト鍵に必要な設定です。次のいずれかの形式で指定してください。

    • --default-encryption-keyCloud KMS 鍵リソース。デフォルトの鍵を追加または変更する場合。例: --default-encryption-key=projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key
    • --clear-default-encryption-key。バケットのデフォルト鍵を削除する場合。

成功した場合、レスポンスは次のようになります。

Updating gs://my-bucket/...
  Completed 1  

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& key_name) {
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetEncryption(
                       gcs::BucketEncryption{key_name}));
  if (!updated) throw std::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";
}

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetEncryption());
  if (!updated) throw std::move(updated).status();

  std::cout << "Successfully removed default KMS key on bucket "
            << updated->name() << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class EnableDefaultKMSKeySample
{
    public Bucket EnableDefaultKMSKey(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string keyLocation = "us-west1",
        string kmsKeyRing = "kms-key-ring",
        string kmsKeyName = "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();
        string keyPrefix = $"projects/{projectId}/locations/{keyLocation}";
        string fullKeyringName = $"{keyPrefix}/keyRings/{kmsKeyRing}";
        string fullKeyName = $"{fullKeyringName}/cryptoKeys/{kmsKeyName}";
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        bucket.Encryption = new Bucket.EncryptionData { DefaultKmsKeyName = fullKeyName };
        var updatedBucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Default KMS key for {bucketName} was set to {kmsKeyName}.");
        return updatedBucket;
    }
}

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketDeleteDefaultKmsKeySample
{
    public Bucket BucketDeleteDefaultKmsKey(string bucketName = "your-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = 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}. ");
        }

        return bucket;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setBucketDefaultKMSKey sets the Cloud KMS encryption key for the bucket.
func setBucketDefaultKMSKey(w io.Writer, bucketName, keyName string) error {
	// bucketName := "bucket-name"
	// keyName := "key"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		Encryption: &storage.BucketEncryption{DefaultKMSKeyName: keyName},
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Default KMS Key Name: %v", bucketAttrsToUpdate.Encryption.DefaultKMSKeyName)
	return nil
}

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// removeBucketDefaultKMSKey removes any default Cloud KMS key set on a bucket.
func removeBucketDefaultKMSKey(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		Encryption: &storage.BucketEncryption{},
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Default KMS key was removed from: %v", bucketName)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class SetBucketDefaultKmsKey {
  public static void setBucketDefaultKmsKey(String projectId, String bucketName, String kmsKeyName)
      throws StorageException {
    // 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"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);

    Bucket updated =
        storage.update(
            bucket.toBuilder().setDefaultKmsKeyName(kmsKeyName).build(),
            BucketTargetOption.metagenerationMatch());

    System.out.println(
        "KMS Key "
            + updated.getDefaultKmsKeyName()
            + "was set to default for bucket "
            + bucketName);
  }
}

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageOptions;

public class RemoveBucketDefaultKmsKey {
  public static void removeBucketDefaultKmsKey(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);
    storage.update(
        bucket.toBuilder().setDefaultKmsKeyName(null).build(),
        BucketTargetOption.metagenerationMatch());

    System.out.println("Default KMS key was removed from " + bucketName);
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function enableDefaultKMSKey() {
  await storage.bucket(bucketName).setMetadata({
    encryption: {
      defaultKmsKeyName,
    },
  });

  console.log(
    `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}.`
  );
}

enableDefaultKMSKey().catch(console.error);

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeDefaultKMSKey() {
  await storage.bucket(bucketName).setMetadata({
    encryption: {
      defaultKmsKeyName: null,
    },
  });

  console.log(`Default KMS key was removed from ${bucketName}`);
}

removeDefaultKMSKey().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。

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']);
}

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

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);
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。

from google.cloud import storage

def enable_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_name
    bucket.patch()

    print(
        "Set default KMS key for bucket {} to {}.".format(
            bucket.name, bucket.default_kms_key_name
        )
    )

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

from google.cloud import storage

def bucket_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 = None
    bucket.patch()

    print(f"Default KMS key was removed from {bucket.name}")
    return bucket

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットにデフォルトの顧客管理の暗号鍵を設定します。

def set_bucket_default_kms_key bucket_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.new
  bucket  = storage.bucket bucket_name

  bucket.default_kms_key = default_kms_key

  puts "Default KMS key for #{bucket.name} was set to #{bucket.default_kms_key}"
end

次のサンプルでは、デフォルトの顧客管理の暗号鍵をバケットから削除します。

def bucket_delete_default_kms_key bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  bucket.default_kms_key = nil

  puts "Default KMS key was removed from #{bucket_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる JSON ファイルを作成します。

    {
      "encryption": {
        "defaultKmsKeyName": "KEY_RESOURCE"
      }
    }

    ここで、KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

    バケットからデフォルトの Cloud KMS 鍵を削除するには、JSON ファイルで次のようにします。

    {
      "encryption": {
        "defaultKmsKeyName": null
      }
    }
  3. cURL を使用して JSON API を呼び出し、PATCH Bucket リクエストを行います。

    curl -X PATCH --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=encryption"

    ここで

    • JSON_FILE_NAME は、手順 2 で作成した JSON ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる XML ファイルを作成します。

    <EncryptionConfiguration>
      <DefaultKmsKeyName>KEY_RESOURCE</DefaultKmsKeyName>
    </EncryptionConfiguration>

    ここで、KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

    バケットからデフォルトの Cloud KMS 鍵を削除するには、XML ファイルで次のようにします。

    <EncryptionConfiguration></EncryptionConfiguration>
  3. cURL を使用して、PUT バケット リクエストと encryptionConfig クエリ文字列パラメータを使用して XML API を呼び出します。

    curl -X PUT --data-binary @XML_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/BUCKET_NAME?encryptionConfig"

    ここで

    • XML_FILE_NAME は、手順 2 で作成した XML ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

バケットのデフォルトの鍵を表示する

バケットのデフォルトとして現在設定されている Cloud KMS 鍵を表示するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、目的のバケットの名前をクリックします。

  3. [バケットの詳細] ページで、[構成] タブをクリックします。

  4. バケットの現在のデフォルトの鍵が [暗号鍵] フィールドに表示されます。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

gcloud storage buckets describe コマンドを使用し、--format フラグを指定します。

gcloud storage buckets describe gs://BUCKET_NAME --format="default(default_kms_key)"

ここで、BUCKET_NAME は鍵を表示するバケットの名前です。例: my-bucket

成功した場合、レスポンスは次のようになります。

default_kms_key: KEY_RESOURCE

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> metadata =
      client.GetBucketMetadata(bucket_name);
  if (!metadata) throw std::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";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。

using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetBucketMetadataSample
{
    public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        Console.WriteLine($"Bucket:\t{bucket.Name}");
        Console.WriteLine($"Acl:\t{bucket.Acl}");
        Console.WriteLine($"Billing:\t{bucket.Billing}");
        Console.WriteLine($"Cors:\t{bucket.Cors}");
        Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");
        Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");
        Console.WriteLine($"Encryption:\t{bucket.Encryption}");
        if (bucket.Encryption != null)
        {
            Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");
        }
        Console.WriteLine($"Id:\t{bucket.Id}");
        Console.WriteLine($"Kind:\t{bucket.Kind}");
        Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");
        Console.WriteLine($"Location:\t{bucket.Location}");
        Console.WriteLine($"LocationType:\t{bucket.LocationType}");
        Console.WriteLine($"Logging:\t{bucket.Logging}");
        Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");
        Console.WriteLine($"Owner:\t{bucket.Owner}");
        Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");
        Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");
        Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");
        Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");
        Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");
        Console.WriteLine($"Updated:\t{bucket.Updated}");
        Console.WriteLine($"Versioning:\t{bucket.Versioning}");
        Console.WriteLine($"Website:\t{bucket.Website}");
        Console.WriteLine($"TurboReplication:\t{bucket.Rpo}");
        if (bucket.Labels != null)
        {
            Console.WriteLine("Labels:");
            foreach (var label in bucket.Labels)
            {
                Console.WriteLine($"{label.Key}:\t{label.Value}");
            }
        }
        return bucket;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。
import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "BucketName: %v\n", attrs.Name)
	fmt.Fprintf(w, "Location: %v\n", attrs.Location)
	fmt.Fprintf(w, "LocationType: %v\n", attrs.LocationType)
	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
	fmt.Fprintf(w, "Turbo replication (RPO): %v\n", attrs.RPO)
	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
	fmt.Fprintf(w, "Metageneration: %v\n", attrs.MetaGeneration)
	fmt.Fprintf(w, "PredefinedACL: %v\n", attrs.PredefinedACL)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.Website != nil {
		fmt.Fprintf(w, "IndexPage: %v\n", attrs.Website.MainPageSuffix)
		fmt.Fprintf(w, "NotFoundPage: %v\n", attrs.Website.NotFoundPage)
	}
	fmt.Fprintf(w, "DefaultEventBasedHold: %v\n", attrs.DefaultEventBasedHold)
	if attrs.RetentionPolicy != nil {
		fmt.Fprintf(w, "RetentionEffectiveTime: %v\n", attrs.RetentionPolicy.EffectiveTime)
		fmt.Fprintf(w, "RetentionPeriod: %v\n", attrs.RetentionPolicy.RetentionPeriod)
		fmt.Fprintf(w, "RetentionPolicyIsLocked: %v\n", attrs.RetentionPolicy.IsLocked)
	}
	fmt.Fprintf(w, "RequesterPays: %v\n", attrs.RequesterPays)
	fmt.Fprintf(w, "VersioningEnabled: %v\n", attrs.VersioningEnabled)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.CORS != nil {
		fmt.Fprintln(w, "CORS:")
		for _, v := range attrs.CORS {
			fmt.Fprintf(w, "\tMaxAge: %v\n", v.MaxAge)
			fmt.Fprintf(w, "\tMethods: %v\n", v.Methods)
			fmt.Fprintf(w, "\tOrigins: %v\n", v.Origins)
			fmt.Fprintf(w, "\tResponseHeaders: %v\n", v.ResponseHeaders)
		}
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetBucketMetadata {
  public static void getBucketMetadata(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

    // Print bucket metadata
    System.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());
    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.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getBucketMetadata() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The ID of your GCS bucket
  // const bucketName = 'your-unique-bucket-name';

  // Get Bucket Metadata
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  console.log(JSON.stringify(metadata, null, 2));
}

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。
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));
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。

from google.cloud import storage

def bucket_metadata(bucket_name):
    """Prints out a bucket's metadata."""
    # bucket_name = 'your-bucket-name'

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    print(f"ID: {bucket.id}")
    print(f"Name: {bucket.name}")
    print(f"Storage Class: {bucket.storage_class}")
    print(f"Location: {bucket.location}")
    print(f"Location Type: {bucket.location_type}")
    print(f"Cors: {bucket.cors}")
    print(f"Default Event Based Hold: {bucket.default_event_based_hold}")
    print(f"Default KMS Key Name: {bucket.default_kms_key_name}")
    print(f"Metageneration: {bucket.metageneration}")
    print(
        f"Public Access Prevention: {bucket.iam_configuration.public_access_prevention}"
    )
    print(f"Retention Effective Time: {bucket.retention_policy_effective_time}")
    print(f"Retention Period: {bucket.retention_period}")
    print(f"Retention Policy Locked: {bucket.retention_policy_locked}")
    print(f"Requester Pays: {bucket.requester_pays}")
    print(f"Self Link: {bucket.self_link}")
    print(f"Time Created: {bucket.time_created}")
    print(f"Versioning Enabled: {bucket.versioning_enabled}")
    print(f"Labels: {bucket.labels}")

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

デフォルトの KMS 鍵を表示するには、バケットのメタデータを表示する手順に沿って、レスポンス内のデフォルトの KMS 鍵フィールドを探します。
def get_bucket_metadata bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  puts "ID:                       #{bucket.id}"
  puts "Name:                     #{bucket.name}"
  puts "Storage Class:            #{bucket.storage_class}"
  puts "Location:                 #{bucket.location}"
  puts "Location Type:            #{bucket.location_type}"
  puts "Cors:                     #{bucket.cors}"
  puts "Default Event Based Hold: #{bucket.default_event_based_hold?}"
  puts "Default KMS Key Name:     #{bucket.default_kms_key}"
  puts "Logging Bucket:           #{bucket.logging_bucket}"
  puts "Logging Prefix:           #{bucket.logging_prefix}"
  puts "Metageneration:           #{bucket.metageneration}"
  puts "Retention Effective Time: #{bucket.retention_effective_at}"
  puts "Retention Period:         #{bucket.retention_period}"
  puts "Retention Policy Locked:  #{bucket.retention_policy_locked?}"
  puts "Requester Pays:           #{bucket.requester_pays}"
  puts "Self Link:                #{bucket.api_url}"
  puts "Time Created:             #{bucket.created_at}"
  puts "Versioning Enabled:       #{bucket.versioning?}"
  puts "Index Page:               #{bucket.website_main}"
  puts "Not Found Page:           #{bucket.website_404}"
  puts "Labels:"
  bucket.labels.each do |key, value|
    puts " - #{key} = #{value}"
  end
  puts "Lifecycle Rules:"
  bucket.lifecycle.each do |rule|
    puts "#{rule.action} - #{rule.storage_class} - #{rule.age} - #{rule.matches_storage_class}"
  end
end

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、目的の fields を含む GET Bucket リクエストで JSON API を呼び出します。

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=encryption"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は鍵を表示するバケットの名前です。例: my-bucket

    次の例のようなレスポンスになります。

    {
      "encryption" : {
         "defaultKmsKeyName": "KEY_RESOURCE"
       },
    }

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、encryption クエリ パラメータが含まれる GET Bucket リクエストで XML API を呼び出します。

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/BUCKET_NAME?encryptionConfig"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は鍵を表示するバケットの名前です。例: my-bucket

    次の例のようなレスポンスになります。

    <EncryptionConfiguration>
      <DefaultKmsKeyName>KEY_RESOURCE</DefaultKmsKeyName>
    </EncryptionConfiguration>

Cloud KMS 鍵を使用してオブジェクトを暗号化する

Cloud KMS 鍵を使用してオブジェクトを個々に暗号化できます。これは、バケットに設定したデフォルトの鍵とは異なる鍵を使用する場合や、バケットにデフォルトの鍵が設定されていない場合に便利です。オブジェクトの暗号化に使用する鍵リソースの名前は、オブジェクトのメタデータに格納されます。

コンソール

Google Cloud コンソールを使用して、オブジェクトごとに Cloud KMS 鍵を指定することはできません。代わりに gcloud CLI またはクライアント ライブラリを使用してください。

コマンドライン

gcloud storage cp コマンドを使用し、--encryption-key フラグを指定します。

gcloud storage cp SOURCE_DATA gs://BUCKET_NAME/OBJECT_NAME --encryption-key=KEY_RESOURCE

ここで

  • SOURCE_DATA は、暗号化するデータのソースの場所です。cp コマンドでサポートされる任意のソースの場所を指定できます。例: gs://my-bucket/pets/old-dog.png
  • BUCKET_NAME は、このコピーコマンドの転送先バケットの名前です。例: my-bucket
  • OBJECT_NAME は、暗号化された最終的なオブジェクトの名前です。例: pets/new-dog.png
  • KEY_RESOURCE は、オブジェクトの暗号化に使用する Cloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& kms_key_name) {
  gcs::ObjectWriteStream stream = client.WriteObject(
      bucket_name, object_name, gcs::KmsKeyName(kms_key_name));

  // Line numbers start at 1.
  for (int lineno = 1; lineno <= 10; ++lineno) {
    stream << lineno << ": placeholder text for CMEK example.\n";
  }

  stream.Close();

  StatusOr<gcs::ObjectMetadata> metadata = std::move(stream).metadata();
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Successfully wrote to object " << metadata->name()
            << " its size is: " << metadata->size()
            << "\nFull metadata: " << *metadata << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class UploadFileWithKmsKeySample
{
    public void UploadFileWithKmsKey(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string keyLocation = "us-west1",
        string kmsKeyRing = "kms-key-ring",
        string kmsKeyName = "key-name",
        string localPath = "my-local-path/my-file-name",
        string objectName = "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();
        string keyPrefix = $"projects/{projectId}/locations/{keyLocation}";
        string fullKeyringName = $"{keyPrefix}/keyRings/{kmsKeyRing}";
        string fullKeyName = $"{fullKeyringName}/cryptoKeys/{kmsKeyName}";

        var storage = StorageClient.Create();
        using var fileStream = File.OpenRead(localPath);
        storage.UploadObject(bucketName, objectName, null, fileStream, new UploadObjectOptions { KmsKeyName = fullKeyName });
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// uploadWithKMSKey writes an object using Cloud KMS encryption.
func uploadWithKMSKey(w io.Writer, bucket, object, keyName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// keyName := "projects/projectId/locations/global/keyRings/keyRingID/cryptoKeys/cryptoKeyID"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	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 = keyName
	if _, err := wc.Write([]byte("top secret")); err != nil {
		return fmt.Errorf("Writer.Write: %w", err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("Writer.Close: %w", err)
	}
	fmt.Fprintf(w, "Uploaded blob %v with KMS key.\n", object)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class UploadKmsEncryptedObject {
  public static void uploadKmsEncryptedObject(
      String projectId, String bucketName, String objectName, String kmsKeyName) {
    // 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"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    byte[] data = "Hello, World!".getBytes(UTF_8);

    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = 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.BlobTargetOption precondition;
    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);
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function uploadFileWithKmsKey() {
  const options = {
    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},
  };

  await storage.bucket(bucketName).upload(filePath, options);

  console.log(`${filePath} uploaded to ${bucketName} using ${kmsKeyName}.`);
}

uploadFileWithKmsKey().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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);
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage

def upload_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 = 0

    blob.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
        )
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def upload_with_kms_key bucket_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.new

  bucket = storage.bucket bucket_name, skip_lookup: true

  file = bucket.create_file local_file_path, file_name, kms_key: kms_key

  puts "Uploaded #{file.name} and encrypted service side using #{file.kms_key}"
end

REST API

JSON API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. オブジェクトのデータをリクエストの本文に追加します。

  3. cURL を使用して、POST Object リクエストで JSON API を呼び出します。

    curl -X POST --data-binary @OBJECT \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: OBJECT_CONTENT_TYPE" \
    "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o?uploadType=media&name=OBJECT_NAME&kmsKeyName=KEY_RESOURCE"

    ここで

    • OBJECT は、アップロードするオブジェクトへのパスです。例: Desktop/dog.png
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • OBJECT_CONTENT_TYPE は、オブジェクトのコンテンツ タイプです。例: image/png
    • BUCKET_NAME は、オブジェクトをアップロードするバケットの名前です。例: my-bucket
    • OBJECT_NAME は、アップロードするオブジェクトの URL エンコードされた名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. オブジェクトのデータをリクエストの本文に追加します。

  3. cURL を使用して、PUT Object リクエストで XML API を呼び出します。

    curl -X PUT --data-binary @OBJECT \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: OBJECT_CONTENT_TYPE" \
    -H "x-goog-encryption-kms-key-name: KEY_RESOURCE" \
    "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    ここで

    • OBJECT は、アップロードするオブジェクトへのパスです。例: Desktop/dog.png
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • OBJECT_CONTENT_TYPE は、オブジェクトのコンテンツ タイプです。例: image/png
    • BUCKET_NAME は、オブジェクトをアップロードするバケットの名前です。例: my-bucket
    • OBJECT_NAME は、アップロードするオブジェクトの URL エンコードされた名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

顧客指定の暗号鍵から Cloud KMS 鍵にローテーションする

オブジェクトが顧客指定の暗号鍵で暗号化されている場合は、オブジェクトを書き換えることによって、Cloud KMS 鍵を使用するようにローテーションできます。

コンソール

Google Cloud コンソールを使用して、オブジェクトごとに暗号鍵を変更することはできません。代わりに gcloud CLI またはクライアント ライブラリを使用してください。

コマンドライン

適切なフラグを指定して、gcloud storage objects update コマンドを使用します。

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --encryption-key=KMS_KEY --decryption-keys=CSEK_KEY

ここで

  • BUCKET_NAME は、鍵をローテーションするオブジェクトを含むバケットの名前です。例: my-bucket
  • OBJECT_NAME は、鍵をローテーションするオブジェクトの名前です。例: pets/dog.png
  • KMS_KEY は、オブジェクトの暗号化に使用する Cloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key
  • CSEK_KEY は、オブジェクトで使用されている現在の顧客指定の暗号鍵です。

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& old_csek_key_base64,
   std::string const& 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) throw std::move(metadata).status();

  std::cout << "Changed object " << metadata->name() << " in bucket "
            << metadata->bucket()
            << " from using CSEK to CMEK key.\nFull Metadata: " << *metadata
            << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class ObjectCsekToCmekSample
{
    public void ObjectCsekToCmek(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name",
        string currrentEncryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=",
        string keyLocation = "us-west1",
        string kmsKeyRing = "kms-key-ring",
        string kmsKeyName = "key-name")
    {
        string keyPrefix = $"projects/{projectId}/locations/{keyLocation}";
        string fullKeyringName = $"{keyPrefix}/keyRings/{kmsKeyRing}";
        string fullKeyName = $"{fullKeyringName}/cryptoKeys/{kmsKeyName}";
        var storage = StorageClient.Create();

        using var outputStream = new MemoryStream();
        storage.DownloadObject(bucketName, objectName, outputStream, new DownloadObjectOptions()
        {
            EncryptionKey = EncryptionKey.Create(Convert.FromBase64String(currrentEncryptionKey))
        });

        outputStream.Position = 0;

        storage.UploadObject(bucketName, objectName, null, outputStream, new UploadObjectOptions()
        {
            KmsKeyName = fullKeyName
        });

        Console.WriteLine($"Object {objectName} in bucket {bucketName} is now managed" +
            $" by the KMS key ${kmsKeyName}  instead of a customer-supplied encryption key");
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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(w io.Writer, bucket, object string, encryptionKey []byte, kmsKeyName string) 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)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// 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)
	if err != nil {
		return fmt.Errorf("object.Attrs: %w", err)
	}
	o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	// You can't change an object's encryption key directly. Instead, you must
	// rewrite the object using the new key.
	src := o.Key(encryptionKey)
	c := o.CopierFrom(src)
	c.DestinationKMSKeyName = kmsKeyName
	if _, err := c.Run(ctx); err != nil {
		return fmt.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)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ChangeObjectCsekToKms {
  public static void changeObjectFromCsekToKms(
      String projectId,
      String bucketName,
      String objectName,
      String decryptionKey,
      String kmsKeyName) {
    // 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";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = 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.BlobSourceOption precondition =
        Storage.BlobSourceOption.generationMatch(blob.getGeneration());

    Storage.CopyRequest request =
        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");
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function changeFileCSEKToCMEK() {
  const rotateEncryptionKeyOptions = {
    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);

  await storage
    .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);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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
    );
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage

def object_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 = None
    token = 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.generation

    while True:
        token, bytes_rewritten, total_bytes = destination_blob.rewrite(
            source_blob, token=token, if_generation_match=generation_match_precondition
        )
        if token is None:
            break

    print(
        "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
        )
    )
    return destination_blob

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def object_csek_to_cmek bucket_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.new
  bucket = storage.bucket bucket_name, skip_lookup: true

  file = bucket.file file_name, encryption_key: encryption_key

  file.rotate encryption_key: encryption_key, new_kms_key: kms_key_name

  puts "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

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、POST Object リクエストで JSON API を呼び出します。

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Length: 0" \
      -H "x-goog-copy-source-encryption-algorithm: AES256" \
      -H "x-goog-copy-source-encryption-key: OLD_ENCRYPTION_KEY" \
      -H "x-goog-copy-source-encryption-key-sha256: HASH_OF_OLD_KEY" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME?kmsKeyName=KEY_RESOURCE"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • OLD_ENCRYPTION_KEY は、オブジェクトの暗号化に現在使用されている AES-256 鍵です。
    • HASH_OF_OLD_KEY は、AES-256 鍵の現在の SHA-256 ハッシュです。
    • BUCKET_NAME は、該当するオブジェクトが格納されているバケットの名前です。例: my-bucket
    • OBJECT_NAME は、鍵をローテーションするオブジェクトの URL エンコードされた名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • KEY_RESOURCECloud KMS 鍵リソースです。例: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

XML API

XML API では、オブジェクトの書き換えによる顧客指定の暗号鍵から Cloud KMS 鍵へのローテーションはサポートされていません。XML API を使用してこのようなローテーションを行うには、次のようにします。

  1. 既存のオブジェクトをダウンロードする
  2. Cloud KMS 鍵を使用してオブジェクトを再アップロードする

オブジェクトの暗号化に使用された鍵を特定する

オブジェクトの暗号化に使用された Cloud KMS 鍵を確認するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、必要なオブジェクトを含むバケットの名前をクリックします。

    [バケットの詳細] ページが開き、[オブジェクト] タブが選択されています。

  3. フォルダ内にあるオブジェクトに移動します。

  4. [暗号化] 列でそのオブジェクトのエントリにカーソルを合わせます。

    鍵の名前とバージョンは次の形式になります。

    LOCATION/KEY_RING_NAME/KEY_NAME/KEY_VERSION

コマンドライン

gcloud storage objects describe コマンドを使用し、--format フラグを指定します。

gcloud storage objects describe gs://BUCKET_NAME/OBJECT_NAME --format="default(kms_key)"

ここで

  • BUCKET_NAME は、暗号化されたオブジェクトが格納されているバケットの名前です。例: my-bucket
  • OBJECT_NAME は暗号化されたオブジェクトの名前です。例: pets/dog.png

成功した場合、レスポンスは次のようになります。

kms_key: projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/1

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> metadata =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!metadata) throw std::move(metadata).status();

  std::cout << "KMS key on object " << metadata->name() << " in bucket "
            << metadata->bucket() << ": " << metadata->kms_key_name() << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

オブジェクトに関連付けられた KMS 鍵を表示するには、オブジェクトのメタデータを表示する手順に沿って、レスポンスの KMS 鍵名フィールドを確認します。

using Google.Cloud.Storage.V1;
using System;

public class GetMetadataSample
{
    public Google.Apis.Storage.v1.Data.Object GetMetadata(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions { 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($"Size:\t{storageObject.Size}");
        Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");
        Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");
        Console.WriteLine($"Updated:\t{storageObject.Updated}");
        bool eventBasedHold = storageObject.EventBasedHold ?? false;
        Console.WriteLine("Event-based hold enabled? {0}", eventBasedHold);
        bool temporaryHold = storageObject.TemporaryHold ?? false;
        Console.WriteLine("Temporary hold enabled? {0}", temporaryHold);
        Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");
        if (storageObject.Metadata != null)
        {
            Console.WriteLine("Metadata: ");
            foreach (var metadata in storageObject.Metadata)
            {
                Console.WriteLine($"{metadata.Key}:\t{metadata.Value}");
            }
        }
        Console.WriteLine($"CustomTime:\t{storageObject.CustomTime}");
        return storageObject;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

オブジェクトに関連付けられた KMS 鍵を表示するには、オブジェクトのメタデータを表示する手順に沿って、レスポンスの KMS 鍵名フィールドを確認します。
import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getMetadata prints all of the object attributes.
func getMetadata(w io.Writer, bucket, object string) (*storage.ObjectAttrs, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return nil, 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, "\n\nMetadata\n")
	for key, value := range attrs.Metadata {
		fmt.Fprintf(w, "\t%v = %v\n", key, value)
	}
	return attrs, nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

オブジェクトに関連付けられた KMS 鍵を表示するには、オブジェクトのメタデータを表示する手順に沿って、レスポンスの KMS 鍵名フィールドを確認します。

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;
import java.util.Map;

public class GetObjectMetadata {
  public static void getObjectMetadata(String projectId, String bucketName, String blobName)
      throws StorageException {
    // 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";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Select all fields
    // Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROL
    Blob blob =
        storage.get(bucketName, blobName, Storage.BlobGetOption.fields(Storage.BlobField.values()));

    // Print blob metadata
    System.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: " + new Date(blob.getCreateTime()));
    System.out.println("Last Metadata Update: " + new Date(blob.getUpdateTime()));
    Boolean temporaryHoldIsEnabled = (blob.getTemporaryHold() != null && blob.getTemporaryHold());
    System.out.println("temporaryHold: " + (temporaryHoldIsEnabled ? "enabled" : "disabled"));
    Boolean eventBasedHoldIsEnabled =
        (blob.getEventBasedHold() != null && blob.getEventBasedHold());
    System.out.println("eventBasedHold: " + (eventBasedHoldIsEnabled ? "enabled" : "disabled"));
    if (blob.getRetentionExpirationTime() != null) {
      System.out.println("retentionExpirationTime: " + new Date(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());
      }
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

オブジェクトに関連付けられた KMS 鍵を表示するには、オブジェクトのメタデータを表示する手順に沿って、レスポンスの KMS 鍵名フィールドを確認します。
/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getMetadata() {
  // Gets the metadata for the file
  const [metadata] = await storage
    .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: ${new Date(metadata.timeCreated)}`);
  console.log(`Last Metadata Update: ${new Date(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: ${new Date(metadata.retentionExpirationTime)}`
    );
  }
  if (metadata.metadata) {
    console.log('\n\n\nUser metadata:');
    for (const key in metadata.metadata) {
      console.log(`${key}=${metadata.metadata[key]}`);
    }
  }
}

getMetadata().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

オブジェクトに関連付けられた KMS 鍵を表示するには、オブジェクトのメタデータを表示する手順に沿って、レスポンスの KMS 鍵名フィールドを確認します。
use Google\Cloud\Storage\StorageClient;

/**
 * List object metadata.
 *
 * @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')
 */
function object_metadata(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $info = $object->info();
    if (isset($info['name'])) {
        printf('Blob: %s' . PHP_EOL, $info['name']);
    }
    if (isset($info['bucket'])) {
        printf('Bucket: %s' . PHP_EOL, $info['bucket']);
    }
    if (isset($info['storageClass'])) {
        printf('Storage class: %s' . PHP_EOL, $info['storageClass']);
    }
    if (isset($info['id'])) {
        printf('ID: %s' . PHP_EOL, $info['id']);
    }
    if (isset($info['size'])) {
        printf('Size: %s' . PHP_EOL, $info['size']);
    }
    if (isset($info['updated'])) {
        printf('Updated: %s' . PHP_EOL, $info['updated']);
    }
    if (isset($info['generation'])) {
        printf('Generation: %s' . PHP_EOL, $info['generation']);
    }
    if (isset($info['metageneration'])) {
        printf('Metageneration: %s' . PHP_EOL, $info['metageneration']);
    }
    if (isset($info['etag'])) {
        printf('Etag: %s' . PHP_EOL, $info['etag']);
    }
    if (isset($info['crc32c'])) {
        printf('Crc32c: %s' . PHP_EOL, $info['crc32c']);
    }
    if (isset($info['md5Hash'])) {
        printf('MD5 Hash: %s' . PHP_EOL, $info['md5Hash']);
    }
    if (isset($info['contentType'])) {
        printf('Content-type: %s' . PHP_EOL, $info['contentType']);
    }
    if (isset($info['temporaryHold'])) {
        printf('Temporary hold: %s' . PHP_EOL, ($info['temporaryHold'] ? 'enabled' : 'disabled'));
    }
    if (isset($info['eventBasedHold'])) {
        printf('Event-based hold: %s' . PHP_EOL, ($info['eventBasedHold'] ? 'enabled' : 'disabled'));
    }
    if (isset($info['retentionExpirationTime'])) {
        printf('Retention Expiration Time: %s' . PHP_EOL, $info['retentionExpirationTime']);
    }
    if (isset($info['customTime'])) {
        printf('Custom Time: %s' . PHP_EOL, $info['customTime']);
    }
    if (isset($info['metadata'])) {
        printf('Metadata: %s' . PHP_EOL, print_r($info['metadata'], true));
    }
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage

def object_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_name

    print(f"The KMS key of a blob is {blob.kms_key_name}")
    return kms_key

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

オブジェクトに関連付けられた KMS 鍵を表示するには、オブジェクトのメタデータを表示する手順に沿って、レスポンスの KMS 鍵名フィールドを確認します。
def get_metadata bucket_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.new
  bucket  = storage.bucket bucket_name
  file    = bucket.file file_name

  puts "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.each do |key, value|
    puts " - #{key} = #{value}"
  end
end

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、GET Object リクエストで JSON API を呼び出します。

    curl -X GET \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?fields=kmsKeyName"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、暗号化されたオブジェクトが格納されているバケットの名前です。例: my-bucket
    • OBJECT_NAME は、暗号化されたオブジェクトの URL エンコードされた名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、GET Object リクエストで XML API を呼び出します。

    curl -X GET \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?encryption"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、暗号化されたオブジェクトが格納されているバケットの名前です。例: my-bucket
    • OBJECT_NAME は、暗号化されたオブジェクトの URL エンコードされた名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png

オブジェクトを復号する

Cloud KMS 鍵で暗号化されたオブジェクトの復号は、関連するサービス エージェントがその鍵にアクセスできる限り、自動的に実行されます。詳細については、顧客管理の暗号鍵を使用したサービス エージェントをご覧ください。

次のステップ