バケットの暗号化タイプを適用または制限する

このドキュメントでは、Cloud Storage バケット内の新しいオブジェクトで許可または制限される暗号化方法を構成する方法について説明します。バケット内で作成される新しいオブジェクトに対して、標準の暗号化(Google のデフォルトの暗号化)、顧客管理の暗号鍵(CMEK)、顧客指定の暗号鍵(CSEK)の使用を適用または制限するようにバケットを構成できます。

たとえば、暗号鍵の管理に関するコンプライアンス要件を満たすために、すべての新しいオブジェクトを標準暗号化または CMEK で暗号化し、顧客提供の暗号鍵の使用を制限できます。

使用可能な暗号化方法の詳細については、データ暗号化オプションをご覧ください。

Cloud Storage は、オブジェクトのアップロード、オブジェクトのコピー、オブジェクトの構成、削除済み(復元可能)オブジェクトの復元など、新しいオブジェクトを作成するすべてのアクションに暗号化構成を適用します。

始める前に

バケットの暗号化の適用を構成するために必要な権限を取得するには、バケットに対するストレージ管理者 roles/storage.admin)IAM ロールを付与するよう管理者に依頼してください。ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

この事前定義ロールには、バケットの暗号化の適用を構成するために必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

バケットの暗号化適用を構成するには、次の権限が必要です。

  • 新しいバケットを作成するときに構成を設定します。 storage.buckets.create
  • 既存のバケットの構成を更新します。 storage.buckets.update

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

暗号化タイプを適用するバケットを作成する

新しいバケットを作成するときに、バケット内のオブジェクトに対して許可または制限する暗号化方式を指定できます。

バケットにデフォルトの Cloud KMS 鍵を設定する場合は、CMEK または顧客指定の暗号鍵を使用した暗号化も許可する必要があります。

gcloud

  1. 次の情報が含まれる JSON ファイルを作成します。

    {
      "gmekEnforcement": {"restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"},
      "cmekEnforcement": {"restrictionMode": "CMEK_RESTRICTION_MODE"},
      "csekEnforcement": {"restrictionMode": "CSEK_RESTRICTION_MODE"}
    }

    次のように置き換えます。

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: このバケットでオブジェクトを作成する際に、標準暗号化(Google のデフォルトの暗号化)を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは標準の暗号化を使用できます。
      • FullyRestricted: 新しいオブジェクトは標準の暗号化を使用できません。
    • CMEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに CMEK を使用した暗号化が許可されているかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは CMEK を使用できます。
      • FullyRestricted: 新しいオブジェクトは CMEK を使用できません。
    • CSEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに、顧客指定の暗号鍵を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できます。
      • FullyRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できません。

    少なくとも 1 つの暗号化タイプを許可する必要があります。特定の暗号化タイプの適用構成を省略すると、その暗号化タイプはデフォルトで許可されます。

  2. gcloud storage buckets create コマンドを使用し、--encryption-enforcement-file フラグを指定します。

    gcloud storage buckets create gs://BUCKET_NAME \
      --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE

    次のように置き換えます。

    • BUCKET_NAME: バケットの名前。
    • ENCRYPTION_ENFORCEMENT_FILE: 前の手順で作成した JSON ファイルのパス。

クライアント ライブラリ

C#

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

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


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

public class BucketSetEncryptionEnforcementConfigSample
{
    /// <summary>
    /// Set the encryption enforcement configuration for a bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="kmsKeyName">
    /// The full resource name of the Cloud KMS key (CMEK). 
    /// Required if <paramref name="enforceCmek"/> is true.
    /// </param>
    /// <param name="enforceCmek">If true, enforces Customer-Managed Encryption Key.</param>
    /// <param name="enforceGmek">If true, enforces Google-Managed Encryption Key.</param>
    /// <param name="enforceCsek">If true, enforces Customer-Supplied Encryption Key.</param>
    public Bucket.EncryptionData SetBucketEncryptionEnforcementConfig(
        string bucketName = "your-unique-bucket-name",
        string kmsKeyName = null,
        bool enforceCmek = false,
        bool enforceGmek = false,
        bool enforceCsek = false)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Encryption == null)
        {
            bucket.Encryption = new Bucket.EncryptionData();
        }

        if (!string.IsNullOrEmpty(kmsKeyName))
        {
            bucket.Encryption.DefaultKmsKeyName = kmsKeyName;
            Console.WriteLine($"Default Key Set: {kmsKeyName}");
        }
        else
        {
            bucket.Encryption.DefaultKmsKeyName = null;
            Console.WriteLine("Default Key Set: None");
        }

        string cmek = (enforceGmek || enforceCsek) ? "FullyRestricted" : "NotRestricted";
        string gmek = (enforceCmek || enforceCsek) ? "FullyRestricted" : "NotRestricted";
        string csek = (enforceCmek || enforceGmek) ? "FullyRestricted" : "NotRestricted";

        string message = enforceCmek ? "CMEK-only enforcement policy"
            : enforceGmek ? "GMEK-only enforcement policy"
            : enforceCsek ? "CSEK-only enforcement policy"
            : "no encryption enforcement policy";

        bucket.Encryption.CustomerManagedEncryptionEnforcementConfig = new Bucket.EncryptionData.CustomerManagedEncryptionEnforcementConfigData { RestrictionMode = cmek };
        bucket.Encryption.CustomerSuppliedEncryptionEnforcementConfig = new Bucket.EncryptionData.CustomerSuppliedEncryptionEnforcementConfigData { RestrictionMode = csek };
        bucket.Encryption.GoogleManagedEncryptionEnforcementConfig = new Bucket.EncryptionData.GoogleManagedEncryptionEnforcementConfigData { RestrictionMode = gmek };

        if (message != null)
        {
            Console.WriteLine($"Bucket {bucketName} updated with {message}");
        }

        var updatedBucket = storage.UpdateBucket(bucket);
        return updatedBucket.Encryption;
    }
}

Go

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

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

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

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

// setBucketEncryptionEnforcementConfig sets a bucket's encryption enforcement configuration.
func setBucketEncryptionEnforcementConfig(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// 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*30)
	defer cancel()

	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, &storage.BucketAttrs{
		GoogleManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
		CustomerManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.NotRestricted,
		},
		CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
	}); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v encryption enforcement policies set.\n", bucketName)
	return nil
}

Java

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

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


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.BucketInfo.CustomerManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.CustomerSuppliedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.EncryptionEnforcementRestrictionMode;
import com.google.cloud.storage.BucketInfo.GoogleManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetBucketEncryptionEnforcementConfig {
  public static void setBucketEncryptionEnforcementConfig(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

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

      // Example 1: Enforce GMEK Only
      setGmekEnforcedPolicy(storage, "g-" + bucketName);

      // Example 2: Enforce CMEK Only
      setCmekEnforcedPolicy(storage, "c-" + bucketName);

      // Example 3: Restrict CSEK (Ransomware Protection)
      restrictCsekPolicy(storage, "rc-" + bucketName);
    }
  }

  public static void setGmekEnforcedPolicy(Storage storage, String bucketName) {
    GoogleManagedEncryptionEnforcementConfig gmekConfig =
        GoogleManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    CustomerManagedEncryptionEnforcementConfig cmekConfig =
        CustomerManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
            .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println(
        "Bucket " + bucket.getName() + " created with GMEK-only enforcement policy.");
  }

  public static void setCmekEnforcedPolicy(Storage storage, String bucketName) {
    GoogleManagedEncryptionEnforcementConfig gmekConfig =
        GoogleManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    CustomerManagedEncryptionEnforcementConfig cmekConfig =
        CustomerManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
            .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println(
        "Bucket " + bucket.getName() + " created with CMEK-only enforcement policy.");
  }

  public static void restrictCsekPolicy(Storage storage, String bucketName) {
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println("Bucket " + bucket.getName() + " created with a policy to restrict CSEK.");
  }
}

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Creates a bucket with specific encryption enforcement (e.g., CMEK-only).
 *
 * @param string $bucketName The ID of your GCS bucket (e.g. "my-bucket").
 * @param string $kmsKeyName The name of the KMS key to be used as the default (e.g. "projects/my-project/...").
 */
function set_bucket_encryption_enforcement_config(string $bucketName, string $kmsKeyName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // This configuration enforces that all objects uploaded to the bucket
    // must use Customer Managed Encryption Keys (CMEK).
    $options = [
        'encryption' => [
            'defaultKmsKeyName' => $kmsKeyName,
            'googleManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted',
            ],
            'customerSuppliedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted',
            ],
            'customerManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'NotRestricted',
            ],
        ],
    ];
    $storage->createBucket($bucketName, $options);

    printf('Bucket %s created with encryption enforcement configuration.' . PHP_EOL, $bucketName);
}

Python

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

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

from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig


def set_bucket_encryption_enforcement_config(bucket_name):
    """Creates a bucket with encryption enforcement configuration."""
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

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

    # Setting restriction_mode to "FullyRestricted" for Google-managed encryption (GMEK)
    # means objects cannot be created using the default Google-managed keys.
    bucket.encryption.google_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    # Setting restriction_mode to "NotRestricted" for Customer-managed encryption (CMEK)
    # ensures that objects ARE permitted to be created using Cloud KMS keys.
    bucket.encryption.customer_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="NotRestricted")
    )

    # Setting restriction_mode to "FullyRestricted" for Customer-supplied encryption (CSEK)
    # prevents objects from being created using raw, client-side provided keys.
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.create()

    print(f"Created bucket {bucket.name} with Encryption Enforcement Config.")

REST API

JSON API

  1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. バケットの設定を含む JSON ファイルを作成します。設定の一覧については、 Buckets: Insert のドキュメントをご覧ください。次の設定では、バケット名と暗号化のみを定義します。

    {
      "name": "BUCKET_NAME",
      "encryption": {
        "googleManagedEncryptionEnforcementConfig": {
          "restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"
        },
        "customerManagedEncryptionEnforcementConfig": {
          "restrictionMode": "CMEK_RESTRICTION_MODE"
        },
        "customerSuppliedEncryptionEnforcementConfig": {
          "restrictionMode": "CSEK_RESTRICTION_MODE"
        }
      }
    }

    次のように置き換えます。

    • BUCKET_NAME: バケットの名前。
    • STANDARD_ENCRYPTION_RESTRICTION_MODE: このバケットでオブジェクトを作成する際に、標準暗号化(Google のデフォルトの暗号化)を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは標準の暗号化を使用できます。
      • FullyRestricted: 新しいオブジェクトは標準の暗号化を使用できません。
    • CMEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに CMEK を使用した暗号化が許可されているかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは CMEK を使用できます。
      • FullyRestricted: 新しいオブジェクトは CMEK を使用できません。
    • CSEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに、顧客指定の暗号鍵を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できます。
      • FullyRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できません。

    少なくとも 1 つの暗号化タイプを許可する必要があります。特定の暗号化タイプの適用構成を省略すると、その暗号化タイプはデフォルトで許可されます。

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

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b?project=PROJECT_ID"

    次のように置き換えます。

    • JSON_FILE_NAME: 前の手順で作成した JSON ファイルのパス。
    • PROJECT_ID: バケットのプロジェクトの ID または番号。

XML API

  1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. バケットの設定を含む XML ファイルを作成します。設定の一覧については、 XML: バケットを作成するのドキュメントをご覧ください。次の設定は、暗号化の適用のみを定義します。

    <CreateBucketConfiguration>
      <EncryptionConfiguration>
        <GoogleManagedEncryptionEnforcement>
          <RestrictionMode>STANDARD_ENCRYPTION_RESTRICTION_MODE</RestrictionMode>
        </GoogleManagedEncryptionEnforcement>
        <CustomerManagedEncryptionEnforcement>
          <RestrictionMode>CMEK_RESTRICTION_MODE</RestrictionMode>
        </CustomerManagedEncryptionEnforcement>
        <CustomerSuppliedEncryptionEnforcement>
          <RestrictionMode>CSEK_RESTRICTION_MODE</RestrictionMode>
        </CustomerSuppliedEncryptionEnforcement>
      </EncryptionConfiguration>
    </CreateBucketConfiguration>

    次のように置き換えます。

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: このバケットでオブジェクトを作成する際に、標準暗号化(Google のデフォルトの暗号化)を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは標準の暗号化を使用できます。
      • FullyRestricted: 新しいオブジェクトは標準の暗号化を使用できません。
    • CMEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに CMEK を使用した暗号化が許可されているかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは CMEK を使用できます。
      • FullyRestricted: 新しいオブジェクトは CMEK を使用できません。
    • CSEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに、顧客指定の暗号鍵を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できます。
      • FullyRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できません。

    少なくとも 1 つの暗号化タイプを許可する必要があります。特定の暗号化タイプの適用構成を省略すると、その暗号化タイプはデフォルトで許可されます。

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

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage.googleapis.com/BUCKET_NAME"

    次のように置き換えます。

    • XML_FILE_NAME: 前の手順で作成した XML ファイルのパス。
    • PROJECT_ID: バケットのプロジェクトの ID または番号。
    • BUCKET_NAME: バケットの名前。

バケットで許可されている暗号化タイプを更新する

既存のバケット内の新しいオブジェクトに許可される暗号化方法を更新する手順は次のとおりです。

バケットにデフォルトの KMS 鍵が設定されている場合、CMEK と顧客指定の暗号鍵の両方を制限することはできません。両方を制限すると、新しいオブジェクトの作成が妨げられるためです。このようなバケットで CMEK または CSEK を許可するか、バケットからデフォルトの Cloud KMS 鍵を削除します。

gcloud

  1. 次の情報が含まれる JSON ファイルを作成します。

    {
      "gmekEnforcement": {"restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"},
      "cmekEnforcement": {"restrictionMode": "CMEK_RESTRICTION_MODE"},
      "csekEnforcement": {"restrictionMode": "CSEK_RESTRICTION_MODE"}
    }

    次のように置き換えます。

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: このバケットでオブジェクトを作成する際に、標準暗号化(Google のデフォルトの暗号化)を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは標準の暗号化を使用できます。
      • FullyRestricted: 新しいオブジェクトは標準の暗号化を使用できません。
    • CMEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに CMEK を使用した暗号化が許可されているかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは CMEK を使用できます。
      • FullyRestricted: 新しいオブジェクトは CMEK を使用できません。
    • CSEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに、顧客指定の暗号鍵を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できます。
      • FullyRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できません。

    少なくとも 1 つの暗号化タイプを許可する必要があります。暗号化タイプを省略すると、既存の構成が保持されます。

  2. gcloud storage buckets update コマンドを使用し、--encryption-enforcement-file フラグを指定します。

    gcloud storage buckets update gs://BUCKET_NAME \
      --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE

    次のように置き換えます。

    • BUCKET_NAME: バケットの名前。
    • ENCRYPTION_ENFORCEMENT_FILE: 前の手順で作成した JSON ファイルのパス。

    更新された構成が有効になるまでに、最長で 2 分かかることがあります。

クライアント ライブラリ

C#

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

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


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

public class BucketUpdateEncryptionEnforcementConfigSample
{
    /// <summary>
    /// Updates the encryption enforcement configuration of the bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="encryptionData">The encryption configuration for the bucket.</param>
    public Bucket.EncryptionData BucketUpdateEncryptionEnforcementConfig(string bucketName = "your-unique-bucket-name", Bucket.EncryptionData encryptionData = null)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Encryption is null
            || (bucket.Encryption.CustomerManagedEncryptionEnforcementConfig is null
                && bucket.Encryption.CustomerSuppliedEncryptionEnforcementConfig is null
                && bucket.Encryption.GoogleManagedEncryptionEnforcementConfig is null))
        {
            Console.WriteLine($"No Encryption Enforcement Configuration found for bucket {bucketName}");
            return bucket.Encryption;
        }

        bucket.Encryption = encryptionData;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"The Encryption Enforcement Configuration has been updated for the bucket {bucketName}");
        return bucket.Encryption;
    }
}

Go

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

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

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

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

// updateBucketEncryptionEnforcementConfig updates a bucket's encryption enforcement configuration.
func updateBucketEncryptionEnforcementConfig(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*30)
	defer cancel()

	bucket := client.Bucket(bucketName)
	if _, err := bucket.Update(ctx, storage.BucketAttrsToUpdate{
		GoogleManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.NotRestricted,
		},
		CustomerManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
		CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
	}); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v encryption enforcement policies updated.\n", bucketName)
	return nil
}

Java

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

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


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo.CustomerManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.CustomerSuppliedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.EncryptionEnforcementRestrictionMode;
import com.google.cloud.storage.BucketInfo.GoogleManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class UpdateBucketEncryptionEnforcementConfig {
  public static void updateBucketEncryptionEnforcementConfig(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket with CMEK and CSEK restricted
    // String bucketName = "your-unique-bucket-name";

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

      Bucket bucket = storage.get(bucketName);
      if (bucket == null) {
        System.out.println("Bucket " + bucketName + " not found.");
        return;
      }

      // 1. Update a specific type (e.g., change GMEK to FULLY_RESTRICTED)
      GoogleManagedEncryptionEnforcementConfig newGmekConfig =
          GoogleManagedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

      // 2. Remove a specific type (e.g., remove CMEK enforcement)
      CustomerManagedEncryptionEnforcementConfig newCmekConfig =
          CustomerManagedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);

      // For the update, need to specify all three configs, so keeping this same as before
      CustomerSuppliedEncryptionEnforcementConfig sameCsekConfig =
          CustomerSuppliedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

      bucket.toBuilder()
          .setGoogleManagedEncryptionEnforcementConfig(newGmekConfig)
          .setCustomerManagedEncryptionEnforcementConfig(newCmekConfig)
          .setCustomerSuppliedEncryptionEnforcementConfig(sameCsekConfig)
          .build()
          .update();

      System.out.println("Encryption enforcement policy updated for bucket " + bucketName);
      System.out.println("GMEK is now fully restricted, and CMEK enforcement has been removed.");
    }
  }
}

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Updates or removes encryption enforcement configurations from a bucket.
 *
 * @param string $bucketName The ID of your GCS bucket (e.g. "my-bucket").
 */
function update_bucket_encryption_enforcement_config(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // Update a specific encryption type's restriction mode
    // This partial update preserves other existing encryption settings.
    $updateOptions = [
        'encryption' => [
            'googleManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted'
            ]
        ]
    ];
    $bucket->update($updateOptions);
    printf('Google-managed encryption enforcement set to FullyRestricted for %s.' . PHP_EOL, $bucketName);

    // Remove all encryption enforcement configurations altogether
    // Setting these values to null removes the policies from the bucket metadata.
    $clearOptions = [
        'encryption' => [
            'defaultKmsKeyName' => null,
            'googleManagedEncryptionEnforcementConfig' => null,
            'customerSuppliedEncryptionEnforcementConfig' => null,
            'customerManagedEncryptionEnforcementConfig' => null,
        ],
    ];

    $bucket->update($clearOptions);
    printf('All encryption enforcement configurations removed from bucket %s.' . PHP_EOL, $bucketName);
}

Python

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

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

from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig


def update_bucket_encryption_enforcement_config(bucket_name):
    """Updates the encryption enforcement policy for a bucket."""
    # The ID of your GCS bucket with GMEK and CSEK restricted
    # bucket_name = "your-unique-bucket-name"

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

    # Update a specific type (e.g., change GMEK to NotRestricted)
    bucket.encryption.google_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="NotRestricted")
    )

    # Update another type (e.g., change CMEK to FullyRestricted)
    bucket.encryption.customer_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    # Keeping CSEK unchanged
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.patch()

    print(f"Encryption enforcement policy updated for bucket {bucket.name}.")

    gmek = bucket.encryption.google_managed_encryption_enforcement_config
    cmek = bucket.encryption.customer_managed_encryption_enforcement_config
    csek = bucket.encryption.customer_supplied_encryption_enforcement_config

    print(f"GMEK restriction mode: {gmek.restriction_mode if gmek else 'None'}")
    print(f"CMEK restriction mode: {cmek.restriction_mode if cmek else 'None'}")
    print(f"CSEK restriction mode: {csek.restriction_mode if csek else 'None'}")

REST API

JSON API

  1. gcloud CLI をインストールして初期化します。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. 次の情報が含まれる JSON ファイルを作成します。

    {
      "encryption": {
        "googleManagedEncryptionEnforcementConfig": {
          "restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"
        },
        "customerManagedEncryptionEnforcementConfig": {
          "restrictionMode": "CMEK_RESTRICTION_MODE"
        },
        "customerSuppliedEncryptionEnforcementConfig": {
          "restrictionMode": "CSEK_RESTRICTION_MODE"
        }
      }
    }

    次のように置き換えます。

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: このバケットでオブジェクトを作成する際に、標準暗号化(Google のデフォルトの暗号化)を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは標準の暗号化を使用できます。
      • FullyRestricted: 新しいオブジェクトは標準の暗号化を使用できません。
    • CMEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに CMEK を使用した暗号化が許可されているかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは CMEK を使用できます。
      • FullyRestricted: 新しいオブジェクトは CMEK を使用できません。
    • CSEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに、顧客指定の暗号鍵を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できます。
      • FullyRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できません。

    少なくとも 1 つの暗号化タイプを許可する必要があります。暗号化タイプを省略すると、既存の構成が保持されます。

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

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=encryption"

    次のように置き換えます。

    • JSON_FILE_NAME: 前の手順で作成した JSON ファイルのパス。
    • BUCKET_NAME: バケットの名前。

    更新された構成が有効になるまでに、最長で 2 分かかることがあります。

XML API

  1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. バケットの暗号化設定を含む XML ファイルを作成します。次の設定では、暗号化の適用構成のみを定義します。

    <EncryptionConfiguration>
      <GoogleManagedEncryptionEnforcement>
        <RestrictionMode>STANDARD_ENCRYPTION_RESTRICTION_MODE</RestrictionMode>
      </GoogleManagedEncryptionEnforcement>
      <CustomerManagedEncryptionEnforcement>
        <RestrictionMode>CMEK_RESTRICTION_MODE</RestrictionMode>
      </CustomerManagedEncryptionEnforcement>
      <CustomerSuppliedEncryptionEnforcement>
        <RestrictionMode>CSEK_RESTRICTION_MODE</RestrictionMode>
      </CustomerSuppliedEncryptionEnforcement>
    </EncryptionConfiguration>

    次のように置き換えます。

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: このバケットでオブジェクトを作成する際に、標準暗号化(Google のデフォルトの暗号化)を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは標準の暗号化を使用できます。
      • FullyRestricted: 新しいオブジェクトは標準の暗号化を使用できません。
    • CMEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに CMEK を使用した暗号化が許可されているかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは CMEK を使用できます。
      • FullyRestricted: 新しいオブジェクトは CMEK を使用できません。
    • CSEK_RESTRICTION_MODE: このバケットでオブジェクトを作成するときに、顧客指定の暗号鍵を使用した暗号化が許可されるかどうか。次の値を使用できます。
      • NotRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できます。
      • FullyRestricted: 新しいオブジェクトは顧客指定の暗号鍵を使用できません。

    少なくとも 1 つの暗号化タイプを許可する必要があります。

  3. cURL を使用して、?encryptionConfig をスコープとする PUT バケット リクエストで XML API を呼び出します。

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?encryptionConfig"

    次のように置き換えます。

    • XML_FILE_NAME: 前の手順で作成した XML ファイルのパス。
    • BUCKET_NAME: バケットの名前。

    更新された構成が有効になるまでに、最長で 2 分かかることがあります。

バケットの暗号化設定を表示する

バケットで許可されている暗号化方法を確認する手順については、バケットのメタデータを取得するをご覧ください。

次のステップ