强制执行或限制存储桶的加密类型

本文档介绍了如何配置 Cloud Storage 存储桶中新对象允许或限制的加密方法。您可以配置存储桶,以强制或限制在存储分区内创建的任何新对象使用标准加密(Google 默认加密)、客户管理的加密密钥 (CMEK) 或客户提供的加密密钥 (CSEK)。

例如,为了满足有关加密密钥管理的合规性要求,您可以要求所有新对象都使用标准加密或 CMEK 进行加密,并限制使用客户提供的加密密钥。

如需详细了解可用的加密方法,请参阅数据加密选项

对于创建新对象的所有操作(例如上传对象、复制对象、组合对象和恢复软删除对象),Cloud Storage 都会强制执行加密配置。

准备工作

如需获得为存储桶配置加密强制执行所需的权限,请让您的管理员为您授予存储桶的 Storage Admin (roles/storage.admin) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色包含为存储桶配置加密强制执行所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需为存储桶配置加密强制执行,您需要具备以下权限:

  • 创建新存储桶时设置配置: storage.buckets.create
  • 更新现有分桶的配置: storage.buckets.update
  • 如果您使用 Google Cloud 控制台执行本页面上的步骤,请执行以下操作:
    • storage.buckets.get
    • storage.buckets.list

您也可以使用自定义角色或其他预定义角色来获取这些权限。

创建强制使用加密类型的存储桶

您可以在创建新存储桶时,指定允许或限制用于存储桶中对象的加密方法。

如果您为存储桶设置了默认 Cloud KMS 密钥,则还必须允许使用 CMEK 或客户提供的加密密钥进行加密。

控制台

  1. 在 Google Cloud 控制台中,转到 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 点击 创建
  3. 创建存储桶页面上,输入您的存储桶信息。完成以下每一步后,点击继续以继续执行后续步骤:

    1. 开始使用部分中,执行以下操作:

      • 输入符合存储桶名称要求的全局唯一的名称。

      • 如需添加存储桶标签,请点击 展开箭头以展开标签部分,点击 添加标签,并为标签指定 keyvalue

    2. 选择数据存储位置部分中,执行以下操作:

      1. 选择位置类型

      2. 使用位置类型的下拉菜单选择一个位置,用于永久存储存储桶中的对象数据。

    3. 选择数据存储方式部分中,执行以下操作:

      1. 为存储桶选择默认存储类别,或者选择 Autoclass 对存储桶数据进行自动存储类别管理。

      2. 针对数据密集型工作负载优化存储部分中,执行以下操作:

        • 如需启用分层命名空间,请选择在此存储桶上启用分层命名空间

        • 如需启用 Rapid Cache,请选择启用 Rapid Cache,然后按以下步骤操作:
          1. 如需创建缓存,请点击配置

          2. 在随即显示的配置缓存设置对话框中,点击所列区域旁边的下拉箭头,然后选择要创建缓存的可用区。

          3. 点击完成

    4. 选择如何控制对对象的访问权限部分中,选择存储桶是否强制执行禁止公开访问,然后为存储桶对象选择统一的存储桶级访问权限。

    5. 选择如何保护对象数据部分中,执行以下操作:

      • 数据保护下,选择您要为存储桶设置的任何选项。

      • 如需更改软删除在删除对象后保留对象的时间,请选中软删除政策复选框,然后选择设置自定义保留时长选项。然后,指定要保留已删除对象的时长。

        如需停用软删除(例如,如果存储桶主要包含短期临时数据),请取消选中软删除政策复选框。

      • 如需选择如何加密对象数据,请点击标有数据加密 展开箭头,然后执行以下操作:

  4. 点击创建

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:新对象无法使用客户提供的加密密钥。

    您必须允许至少一种加密类型。如果您省略了特定加密类型的强制执行配置,则默认允许该加密类型。

  2. 使用带有 --encryption-enforcement-file 标志的 gcloud storage buckets create 命令:

    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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id,
   std::string const& bucket_name) {
  auto create_bucket = [&](std::string const& name,
                           gcs::BucketEncryption encryption) {
    StatusOr<gcs::BucketMetadata> bucket = client.CreateBucketForProject(
        name, project_id, gcs::BucketMetadata().set_encryption(encryption));
    if (!bucket) throw std::move(bucket).status();
    return bucket;
  };

  // Example 1: Enforce GMEK Only
  gcs::BucketEncryption gmek_encryption;
  gmek_encryption.google_managed_encryption_enforcement_config
      .restriction_mode = "NotRestricted";
  gmek_encryption.customer_managed_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  gmek_encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  std::cout << "Bucket "
            << create_bucket("g-" + bucket_name, gmek_encryption)->name()
            << " created with GMEK-only enforcement policy.\n";

  // In GCS, a single project cannot create or delete buckets more often than
  // once every two seconds. We pause to avoid rate limiting.
  std::this_thread::sleep_for(std::chrono::seconds(2));

  // Example 2: Enforce CMEK Only
  gcs::BucketEncryption cmek_encryption;
  cmek_encryption.google_managed_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  cmek_encryption.customer_managed_encryption_enforcement_config
      .restriction_mode = "NotRestricted";
  cmek_encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  std::cout << "Bucket "
            << create_bucket("c-" + bucket_name, cmek_encryption)->name()
            << " created with CMEK-only enforcement policy.\n";

  // In GCS, a single project cannot create or delete buckets more often than
  // once every two seconds. We pause to avoid rate limiting.
  std::this_thread::sleep_for(std::chrono::seconds(2));

  // Example 3: Restrict CSEK (Ransomware Protection)
  gcs::BucketEncryption csek_encryption;
  csek_encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  std::cout << "Bucket "
            << create_bucket("rc-" + bucket_name, csek_encryption)->name()
            << " created with a policy to restrict CSEK.\n";
}

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

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 be used as the 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 setBucketEncryptionEnforcementConfig() {
  const options = {
    encryption: {
      defaultKmsKeyName,
      googleManagedEncryptionEnforcementConfig: {
        restrictionMode: 'FullyRestricted',
      },
      customerSuppliedEncryptionEnforcementConfig: {
        restrictionMode: 'FullyRestricted',
      },
      customerManagedEncryptionEnforcementConfig: {
        restrictionMode: 'NotRestricted',
      },
    },
  };

  const [metadata] = await storage.bucket(bucketName).setMetadata(options);

  console.log(
    `Encryption enforcement configuration updated for bucket ${bucketName}.`
  );
  const enc = metadata.encryption;
  if (enc) {
    console.log(`Default KMS Key: ${enc.defaultKmsKeyName}`);

    const logEnforcement = (label, config) => {
      if (config) {
        console.log(`${label}:`);
        console.log(`  Mode: ${config.restrictionMode}`);
        console.log(`  Effective: ${config.effectiveTime}`);
      }
    };

    logEnforcement(
      'Google Managed (GMEK) Enforcement',
      enc.googleManagedEncryptionEnforcementConfig
    );
    logEnforcement(
      'Customer Managed (CMEK) Enforcement',
      enc.customerManagedEncryptionEnforcementConfig
    );
    logEnforcement(
      'Customer Supplied (CSEK) Enforcement',
      enc.customerSuppliedEncryptionEnforcementConfig
    );
  }
}

setBucketEncryptionEnforcementConfig().catch(console.error);

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

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

def set_bucket_encryption_enforcement_config bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  customer_managed_config = { restriction_mode: "NotRestricted" }
  customer_supplied_config = { restriction_mode: "FullyRestricted" }
  google_managed_config = { restriction_mode: "FullyRestricted" }

  bucket = storage.create_bucket bucket_name do |b|
    b.customer_managed_encryption_enforcement_config = customer_managed_config
    b.customer_supplied_encryption_enforcement_config = customer_supplied_config
    b.google_managed_encryption_enforcement_config = google_managed_config
  end
  puts "Created bucket #{bucket.name} with Encryption Enforcement Config."
end

REST API

JSON API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

  2. 创建一个包含存储桶设置的 JSON 文件。如需查看完整的设置列表,请参阅 存储分区:插入文档。以下设置仅定义了存储桶名称和加密:

    {
      "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:新对象无法使用客户提供的加密密钥。

    您必须允许至少一种加密类型。如果您省略了特定加密类型的强制执行配置,则默认允许该加密类型。

  3. 使用 cURL,通过 POST Bucket 请求调用 JSON API:

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage./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:新对象无法使用客户提供的加密密钥。

    您必须允许至少一种加密类型。如果您省略了特定加密类型的强制执行配置,则默认允许该加密类型。

  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./BUCKET_NAME"

    替换以下内容:

    • XML_FILE_NAME:您在上一步中创建的 XML 文件的路径。
    • PROJECT_ID:存储桶所属项目的 ID 或编号。
    • BUCKET_NAME:相应存储桶的名称。

更新存储桶允许的加密类型

如需更新现有存储桶中允许用于新对象的加密方法,请完成以下步骤。

如果存储桶已设置默认 KMS 密钥,则您无法同时限制 CMEK 和客户提供的加密密钥,因为这样做会阻止新对象的创建。允许在此类存储桶上使用 CMEK 或 CSEK,或者从存储桶中移除默认 Cloud KMS 密钥

控制台

  1. 在 Google Cloud 控制台中,转到 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击相应存储桶的名称。

  3. 点击配置标签页。

  4. 保护部分,点击  修改加密

  5. 加密强制执行规则部分中,针对密钥类型,选择要允许或限制存储桶中新对象的哪些加密类型。

  6. 点击保存

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:新对象无法使用客户提供的加密密钥。

    您必须允许至少一种加密类型。如果您省略加密类型,系统会保留现有配置。

  2. 使用带有 --encryption-enforcement-file 标志的 gcloud storage buckets update 命令:

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

    替换以下内容:

    • BUCKET_NAME:相应存储桶的名称。
    • ENCRYPTION_ENFORCEMENT_FILE:您在上一步中创建的 JSON 文件的路径。

    更新后的配置最多可能需要两分钟才能生效。

客户端库

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> original =
      client.GetBucketMetadata(bucket_name);

  gcs::BucketMetadata updated_metadata = *original;
  gcs::BucketEncryption encryption;
  if (original->has_encryption()) {
    encryption = original->encryption();
  }

  // 1. Update a specific type (e.g., change GMEK to FullyRestricted)
  encryption.google_managed_encryption_enforcement_config.restriction_mode =
      "FullyRestricted";
  // 2. Remove a specific type (e.g., remove CMEK enforcement)
  encryption.customer_managed_encryption_enforcement_config.restriction_mode =
      "NotRestricted";
  // For the update, need to specify all three configs, so keeping this same
  // as before
  encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";

  updated_metadata.set_encryption(encryption);

  StatusOr<gcs::BucketMetadata> updated =
      client.PatchBucket(bucket_name, *original, updated_metadata);
  if (!updated) throw std::move(updated).status();

  std::cout << "Encryption enforcement policy updated for bucket "
            << updated->name() << "\n"
            << "GMEK is now fully restricted, and CMEK enforcement has been "
               "removed.\n";
}

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

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

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

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

async function updateBucketEncryptionEnforcementConfig() {
  const bucket = storage.bucket(bucketName);

  // Update a specific encryption type's restriction mode
  // This partial update preserves other existing encryption settings.
  const updateOptions = {
    encryption: {
      googleManagedEncryptionEnforcementConfig: {
        restrictionMode: 'FullyRestricted',
      },
    },
  };

  await bucket.setMetadata(updateOptions);
  console.log(
    `Google-managed encryption enforcement set to FullyRestricted for ${bucketName}.`
  );

  // Remove all encryption enforcement configurations altogether
  // Setting these values to null removes the policies from the bucket metadata.
  const clearOptions = {
    encryption: {
      defaultKmsKeyName: null,
      googleManagedEncryptionEnforcementConfig: null,
      customerSuppliedEncryptionEnforcementConfig: null,
      customerManagedEncryptionEnforcementConfig: null,
    },
  };

  await bucket.setMetadata(clearOptions);
  console.log(
    `All encryption enforcement configurations removed from bucket ${bucketName}.`
  );
}

updateBucketEncryptionEnforcementConfig().catch(console.error);

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'}")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证


def update_bucket_encryption_enforcement_config bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name
  # Update a specific type (e.g., change GMEK to NotRestricted)
  new_config =  { restriction_mode: "NotRestricted" }

  bucket.update do |b|
    b.google_managed_encryption_enforcement_config = new_config
  end
  puts "Updated google_managed_config to " \
       "#{bucket.google_managed_encryption_enforcement_config.restriction_mode} " \
       "for bucket #{bucket.name}."
end

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:新对象无法使用客户提供的加密密钥。

    您必须允许至少一种加密类型。如果您省略加密类型,系统会保留现有配置。

  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./storage/v1/b/BUCKET_NAME?fields=encryption"

    替换以下内容:

    • JSON_FILE_NAME:您在上一步中创建的 JSON 文件的路径。
    • BUCKET_NAME:相应存储桶的名称。

    更新后的配置最多可能需要两分钟才能生效。

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:新对象无法使用客户提供的加密密钥。

    您必须允许至少一种加密类型。

  3. 使用 cURL 通过范围限定为 ?encryptionConfigPUT Bucket 请求调用 XML API:

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

    替换以下内容:

    • XML_FILE_NAME:您在上一步中创建的 XML 文件的路径。
    • BUCKET_NAME:相应存储桶的名称。

    更新后的配置最多可能需要两分钟才能生效。

查看存储桶的加密设置

如需查看存储桶允许的加密方法,请参阅获取存储桶元数据

后续步骤