使用客户管理的加密密钥

本页面介绍了如何搭配使用 Cloud Key Management Service 加密密钥和 Cloud Storage,内容包括该功能的使用入门、如何在存储分区上使用默认密钥以及如何向各个对象添加密钥。Cloud KMS 加密密钥是“客户管理的加密密钥”,该密钥由 Cloud KMS 创建并由您负责管理。要详细了解此功能(包括可用的国家/地区),请参阅客户管理的加密密钥。如需了解 Cloud Storage 中的其他加密选项,请参阅数据加密选项

前提条件

在 Cloud Storage 中使用此功能之前,您应该:

  1. 为存储加密密钥的项目启用 Cloud KMS API。

    启用 API

  2. 对存储加密密钥的项目拥有足够的权限:

    • 如果您拥有将存储密钥的项目,则您很可能具备必要的权限。

    • 如果您计划创建新的加密密钥环和密钥,您应具备 cloudkms.keyRings.createcloudkms.cryptoKey.create 权限。

    • 无论您计划使用新的还是现有的密钥环和密钥,您都应具备用于加密的密钥的 cloudkms.cryptoKey.setIamPolicy 权限。

      使用此权限,您可为 Cloud Storage 服务帐号授予对 Cloud KMS 密钥的访问权限。

    • 上述权限包含在 roles/cloudkms.admin 角色中。

      有关如何获取此角色或其他 Cloud KMS 角色的说明,请参阅将 IAM 与 Cloud KMS 配合使用

  3. 具备足够的权限来处理 Cloud Storage 存储分区中的对象:

    • 如果您拥有包含该存储分区的项目,则您很可能具备所需的权限。

    • 如果使用 IAM,您应具有 storage.objects.create 权限(以便将对象写入存储分区)以及 storage.objects.get 权限(以便从存储分区读取对象)。有关如何获取具有这些权限的角色(例如 roles/storage.objectAdmin)的说明,请参阅使用 IAM 权限

    • 如果使用 ACL,您应具有存储分区范围内的 WRITER 权限 (以便将对象写入存储分区)以及对象范围内的 READER 权限(以便从存储分区读取对象)。如需了解如何执行此操作的详情,请参阅设置 ACL

  4. 拥有 Cloud KMS 密钥环,并且在密钥环中至少有一个密钥

  5. 获取与包含 Cloud Storage 存储分区的项目关联的服务帐号的电子邮件地址

将 Cloud KMS 密钥分配给服务帐号

要使用客户管理的加密密钥,您必须授权 Cloud Storage 服务帐号使用 Cloud KMS 密钥。

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Key Management Service 密钥浏览器。
    打开 Cloud KMS 密钥浏览器
  2. 点击包含所需密钥的密钥环的名称。

  3. 选中所需密钥对应的复选框。

    右侧窗格中的权限标签变为可用。

  4. 添加成员对话框中,指定要授予访问权限的 Cloud Storage 服务帐号的电子邮件地址。

  5. 选择角色下拉列表中,选择 Cloud KMS CryptoKey Encrypter/Decrypter

  6. 点击添加

gsutil

使用 gsutil kms authorize 命令授权与您的存储分区关联的服务帐号使用 Cloud KMS 密钥加密和解密对象,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil kms authorize -p [PROJECT_STORING_OBJECTS] -k [KEY_RESOURCE]

如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

如果要移除授予的权限,您需要使用 gcloud 命令行工具或 Google Cloud Platform Console。

代码示例

C#

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

        public static void AddMemberToCryptoKeyPolicy(string projectId, string locationId,
            string keyRingId, string cryptoKeyId, string role, string member)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            Policy policy = client.GetIamPolicy(KeyNameOneof.From(cryptoKeyName));
            policy.Bindings.Add(new Binding
            {
                Role = role,
                Members = { member }
            });

            Policy updateResult = client.SetIamPolicy(KeyNameOneof.From(cryptoKeyName), policy);

            foreach (Binding bindingResult in updateResult.Bindings)
            {
                Console.WriteLine($"Role: {bindingResult.Role}");
                foreach (string memberResult in bindingResult.Members)
                {
                    Console.WriteLine($"  Member: {memberResult}");
                }
            }
        }

Go

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

// addMemberRingPolicy adds a new member to a specified IAM role for the key ring
// example keyRingName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID"
func addMemberRingPolicy(keyRingName, member string, role iam.RoleName) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}

	// Get the KeyRing.
	keyRingObj, err := client.GetKeyRing(ctx, &kmspb.GetKeyRingRequest{Name: keyRingName})
	if err != nil {
		return err
	}
	// Get IAM Policy.
	handle := client.KeyRingIAM(keyRingObj)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return err
	}
	// Add Member.
	policy.Add(member, role)
	err = handle.SetPolicy(ctx, policy)
	if err != nil {
		return err
	}
	log.Print("Added member to keyring policy.")
	return nil
}

Java

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

/**
 * Adds the given member to the given key, with the given role.
 *
 * @param projectId The id of the project.
 * @param locationId The location id of the key.
 * @param keyRingId The id of the keyring.
 * @param cryptoKeyId The id of the crypto key.
 * @param member The member to add. Must be in the proper format, eg:
 *
 * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
 *
 * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
 * @param role Must be in one of the following formats: roles/[role]
 * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
 *
 * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
 */
public static Policy addMemberToCryptoKeyPolicy(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
    String role)
    throws IOException {

  // Create the Cloud KMS client.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the cryptoKey version
    String keyName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

    // Get the current IAM policy
    Policy iamPolicy = client.getIamPolicy(keyName);

    // Create a new binding with the selected role and member
    Binding newBinding = Binding.newBuilder()
        .setRole(role)
        .addMembers(member)
        .build();

    // Create a new IAM policy containing the existing settings plus the new binding.
    Policy newPolicy = Policy.newBuilder()
        .mergeFrom(iamPolicy)
        .addBindings(newBinding)
        .build();

    // Set the new IAM Policy.
    Policy policyResult = client.setIamPolicy(keyName, newPolicy);

    return policyResult;
  }
}

Node.js

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

async function addMemberToCryptoKeyPolicy(
  projectId = 'your-project-id', // Your GCP Project Id
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key
  member = 'user:dev@example.com', // Member to add to the crypto key
  role = 'roles/viewer' // Role to give the member
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring
  const locationId = 'global';

  // Get the full path to the crypto key
  const resource = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Gets the IAM policy of a crypto key
  const [result] = await client.getIamPolicy({resource});
  let policy = Object.assign({bindings: []}, result);
  const index = policy.bindings.findIndex(binding => binding.role === role);

  // Add the role/member combo to the policy
  const members = [];
  const binding = Object.assign({role, members}, policy.bindings[index]);
  if (index === -1) {
    policy.bindings.push(binding);
  }
  if (!binding.members.includes(member)) {
    binding.members.push(member);
  }

  // Adds the member/role combo to the policy of the crypto key
  [policy] = await client.setIamPolicy({resource, policy});
  console.log(
    `${member}/${role} combo added to policy for crypto key ${cryptoKeyId}.`
  );
  if (policy.bindings) {
    policy.bindings.forEach(binding => {
      if (binding.members && binding.members.length) {
        console.log(`${binding.role}:`);
        binding.members.forEach(member => {
          console.log(`  ${member}`);
        });
      }
    });
  } else {
    console.log(`Policy for crypto key ${cryptoKeyId} is empty.`);
  }
}

PHP

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

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Iam\V1\Binding;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';
// $cryptoKeyId = 'The KMS key ID';
// $member = 'Must be in the format "user:$userEmail" or "serviceAccount:$serviceAccountEmail"';
// $role = 'Must be in the format "roles/$role", "organizations/$organizationId/roles/$role", or "projects/$projectId/roles/$role"';

$kms = new KeyManagementServiceClient();

// The resource name of the CryptoKey.
$cryptoKeyName = $kms->cryptoKeyName($projectId, $locationId, $keyRingId, $cryptoKeyId);

// Get the current IAM policy and add the new account to it.
$policy = $kms->getIamPolicy($cryptoKeyName);
$bindings = $policy->getBindings();
$bindings[] = new Binding([
    'members' => [$member],
    'role' => $role,
]);
$policy->setBindings($bindings);

// Set the new IAM Policy.
$kms->setIamPolicy($cryptoKeyName, $policy);

printf('Member %s added to policy for cryptoKey %s in keyRing %s' . PHP_EOL, $member, $cryptoKeyId, $keyRingId);

Python

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

def add_member_to_crypto_key_policy(
        project_id, location_id, key_ring_id, crypto_key_id, member, role):
    """Adds a member with a given role to the Identity and Access Management
    (IAM) policy for a given CryptoKey associated with a KeyRing."""

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the CryptoKey.
    resource = client.crypto_key_path_path(project_id, location_id,
                                           key_ring_id, crypto_key_id)
    # Get the current IAM policy.
    policy = client.get_iam_policy(resource)

    # Add member
    policy.bindings.add(
        role=role,
        members=[member])

    # Update the IAM Policy.
    client.set_iam_policy(resource, policy)

    # Print results
    print('Member {} added with role {} to policy for CryptoKey {} \
           in KeyRing {}'.format(member, role, crypto_key_id, key_ring_id))

Ruby

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

# project_id  = "Your Google Cloud project ID"
# location_id = "The location of the key ring"
# key_ring_id = "The ID of the key ring"
# member      = "Member to add to the key ring policy"
# role        = "Role assignment for new member"

require "google/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The key ring to use
key_ring =
  CloudKMS::KeyManagementServiceClient.key_ring_path project_id, location_id, key_ring_id

# Get the current IAM policy
policy = client.get_iam_policy key_ring

# Add new member to current bindings
policy.bindings ||= []
policy.bindings << Google::Iam::V1::Binding.new(members: [member], role: role)

# Update IAM policy
client.set_iam_policy key_ring, policy

puts "Member #{member} added to policy for " +
     "key ring #{key_ring_id}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件,并将 [VALUES_IN_BRACKETS] 替换为适当的值:

    {
      "policy": {
        "bindings": {
          "role": "roles/cloudkms.cryptoKeyEncrypterDecrypter",
          "members": "[SERVICE_ACCOUNT_EMAIL_ADDRESS]"
        },
      }
    }
  3. 使用 cURL,通过 POST setIamPolicy 请求调用 Cloud KMS API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

    如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

XML API

您不能使用 XML API 将 Cloud KMS 分配给服务帐号。请改用其他 Cloud Storage 工具,例如 gsutil。

使用默认加密密钥

添加或更改存储分区的默认密钥

要添加或更改在将对象写入存储分区时默认使用的 Cloud KMS 密钥:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击所需的存储分区。

  3. 点击页面顶部的修改存储分区

  4. 在“修改存储分区”页面中,点击可展开的显示高级设置

  5. 如果存储分区当前未使用 Cloud KMS 密钥,请选择客户管理的密钥单选按钮。

  6. 在与客户管理的密钥关联的下拉菜单中,选择一个可用密钥。

  7. 点击保存

gsutil

使用 gsutil kms encryption 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil kms encryption -k [KEY_RESOURCE] gs://[BUCKET_NAME]

如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

如果成功,响应将类似于如下内容:

Authorized service account [SERVICE_ACCOUNT_NAME] to use key:
[KEY_RESOURCE]

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string key_name) {
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetEncryption(
                       gcs::BucketEncryption{key_name}));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  if (!updated_metadata->has_encryption()) {
    std::cerr << "The change to set the encryption attribute on bucket "
              << updated_metadata->name()
              << " was sucessful, 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_metadata->name() << " to "
            << updated_metadata->encryption().default_kms_key_name << "."
            << "\nFull metadata: " << *updated_metadata << "\n";
}

C#

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

private void AddBucketDefaultKmsKey(string bucketName,
    string keyLocation, string kmsKeyRing, string kmsKeyName)
{
    string KeyPrefix = $"projects/{s_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, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	Encryption: &storage.BucketEncryption{DefaultKMSKeyName: keyName},
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of the existing bucket to set a default KMS key for, e.g. "my-bucket"
// String bucketName = "my-bucket"

// The name of the KMS-key to use as a default
// Key names are provided in the following format:
// 'projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>'
// String kmsKeyName = ""

BucketInfo bucketInfo =
    BucketInfo.newBuilder(bucketName).setDefaultKmsKeyName(kmsKeyName).build();

Bucket bucket = storage.update(bucketInfo);

System.out.println("Default KMS Key Name: " + bucket.getDefaultKmsKeyName());

Node.js

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const defaultKmsKeyName = 'KMS key resource id, e.g. my-key';

// Enables a default KMS key for the bucket
await storage.bucket(bucketName).setMetadata({
  encryption: {
    defaultKmsKeyName,
  },
});

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

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 * @param string $kmsKeyName KMS key ID to use as the default KMS key.
 *
 * @return void
 */
function enable_default_kms_key($projectId, $bucketName, $kmsKeyName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $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']);
}

Python

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

"""Sets a bucket's default KMS 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))

Ruby

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

# project_id      = "Your Google Cloud project ID"
# bucket_name     = "Name of your Google Cloud Storage bucket"
# default_kms_key = "KMS key resource id"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
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}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件,并将 [VALUES_IN_BRACKETS] 替换为适当的值:

    {
      "encryption": {
        "defaultKmsKeyName": "[KEY_RESOURCE]"
      }
    }

    如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .xml 文件,并将 [VALUES_IN_BRACKETS] 替换为适当的值:

    <EncryptionConfiguration>
      <DefaultKmsKeyName>[KEY_RESOURCE]</DefaultKmsKeyName>
    </EncryptionConfiguration>

    如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

  3. 使用 cURL,通过 PUT Bucket 请求和 encryption 查询字符串参数调用 XML API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

查看存储分区的默认密钥

要查看当前设为存储分区的默认密钥的 Cloud KMS 密钥,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击所需的存储分区。

  3. 在存储分区详细信息页面中,点击概览标签。

  4. 存储分区的当前默认密钥显示在加密密钥字段中。

gsutil

使用 gsutil kms encryption 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil kms encryption gs://[BUCKET_NAME]

如果成功,响应将类似于如下内容:

Default encryption key for gs://[BUCKET_NAME]:
[KEY_RESOURCE]

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过包含所需 fieldsGET Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

    响应类似于以下示例:

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

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过包含 encryption 查询参数的 GET Bucket 请求调用 XML API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

    响应类似于以下示例:

    <EncryptionConfiguration>
      <DefaultKmsKeyName>[KEY_RESOURCE]</DefaultKmsKeyName>
    </EncryptionConfiguration>

从存储分区中移除默认密钥

要移除存储分区中设置的任何默认 Cloud KMS 密钥,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击所需的存储分区。

  3. 点击页面顶部的修改存储分区

  4. 在“修改存储分区”页面中,点击可展开的显示高级设置

  5. 选择 Google 管理的密钥单选按钮。

  6. 点击保存

gsutil

使用 gsutil kms encryption 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil kms encryption -d gs://[BUCKET_NAME]

如果成功,响应将类似于如下内容:

Clearing default encryption key for gs://[BUCKET_NAME]...

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "encryption": {
        "defaultKmsKeyName": null
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .xml 文件:

    <EncryptionConfiguration></EncryptionConfiguration>
  3. 使用 cURL,通过 PUT Bucket 请求和 encryption 查询字符串参数调用 XML API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

使用 Cloud KMS 密钥加密对象

您可以使用 Cloud KMS 密钥加密单个对象。如果您要使用与存储分区上设置的默认密钥不同的密钥,或者您没有在存储分区上设置默认密钥,则此功能非常有用。

控制台

您不能使用 GCP Console 来加密单个对象。请改用 gsutil 或客户端库。

gsutil

  1. 将以下选项添加到 .boto 配置文件[GSUtil] 部分: :

    encryption_key = [KEY_RESOURCE]

    如需了解密钥的预期格式,请参阅密钥资源

  2. 像往常一样将对象写入存储分区,例如,使用 gsutil cpgsutil rewrite

代码示例

C++

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

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

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

C#

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

        private void UploadEncryptedFileWithKmsKey(string bucketName,
            string keyLocation, string kmsKeyRing, string kmsKeyName,
            string localPath, string objectName = null)
        {
            string KeyPrefix = $"projects/{s_projectId}/locations/{keyLocation}";
            string FullKeyringName = $"{KeyPrefix}/keyRings/{kmsKeyRing}";
            string FullKeyName = $"{FullKeyringName}/cryptoKeys/{kmsKeyName}";

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

Go

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

obj := client.Bucket(bucket).Object(object)
// Encrypt the object's contents
wc := obj.NewWriter(ctx)
wc.KMSKeyName = keyName
if _, err := wc.Write([]byte("top secret")); err != nil {
	return err
}
if err := wc.Close(); err != nil {
	return err
}

Java

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

byte[] data = "Hello, World!".getBytes(UTF_8);

// The name of the existing bucket to set a default KMS key for, e.g. "my-bucket"
// String bucketName = "my-bucket"

// The name of the KMS-key to use as a default
// Key names are provided in the following format:
// 'projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>'
// String kmsKeyName = ""

BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, data, BlobTargetOption.kmsKeyName(kmsKeyName));

Node.js

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';
// const kmsKeyName = 'KMS key resource id, e.g. my-key';

// Uploads a local file to the bucket with the kms key
await storage.bucket(bucketName).upload(filename, {
  kmsKeyName,
});

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

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Upload a file using KMS encryption.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of the object.
 * @param string $source the path to the file to upload.
 * @param string $kmsKeyName KMS key ID used to encrypt objects server side.
 *
 * @return Psr\Http\Message\StreamInterface
 */
function upload_with_kms_key($projectId, $bucketName, $objectName, $source, $kmsKeyName)
{
    $storage = new StorageClient([
        'projectId' => $projectId,
    ]);
    $file = fopen($source, 'r');
    $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 参考文档

"""Uploads a file to the bucket, encrypting it with the given KMS key."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name, kms_key_name=kms_key_name)
blob.upload_from_filename(source_file_name)

print('File {} uploaded to {} with encryption key {}.'.format(
    source_file_name,
    destination_blob_name,
    kms_key_name))

Ruby

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

# project_id        = "Your Google Cloud project ID"
# bucket_name       = "Your Google Cloud Storage bucket name"
# local_file_path   = "Path to local file to upload"
# storage_file_path = "Path to store the file in Google Cloud Storage"
# kms_key           = "KMS key resource id"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id

bucket = storage.bucket bucket_name

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

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

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 将对象的数据添加到请求正文。

  3. 使用 cURL,通过 POST Object 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

    如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 将对象的数据添加到请求正文。

  3. 使用 cURL,通过 PUT Object 请求调用 XML API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

    如需了解 [KEY_RESOURCE] 的预期格式,请参阅关键资源

确定用于加密对象的密钥

要查找用于加密对象的 Cloud KMS 密钥的名称,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 导航到相关存储分区中的所需对象。

  3. 加密列中,将鼠标悬停在所需对象的条目上。

    密钥名称采用以下格式显示:

    [LOCATION]/[KEY_RING_NAME]/[KEY_NAME]

gsutil

使用带有 -L 标志的 gsutil ls 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil ls -L gs://[BUCKET_NAME]/[OBJECT_NAME]

如果成功,则响应会包含密钥名称:

gs://[BUCKET_NAME]/[OBJECT_NAME]:
...
KMS key: [KEY_RESOURCE]
...

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Object 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Object 请求调用 XML API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

解密对象

系统会自动解密使用客户管理的加密密钥加密的对象,前提是相关服务帐号有权访问密钥。有关详情,请参阅具有客户管理的加密密钥的服务帐号

后续步骤

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面