使用客戶代管的加密金鑰

本頁面說明如何搭配使用 Cloud Storage 與 Cloud Key Management Service 加密金鑰,包括開始使用功能、使用值區預設的金鑰,以及新增金鑰到個別物件。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 角色的說明,請參閱對 Cloud KMS 使用身分與存取權管理一文。

  3. 針對要在 Cloud Storage 值區中使用的物件取得足夠的權限:

    • 如果您擁有包含該值區的專案,代表您非常有可能已經具備必要權限。

    • 如果您使用身分與存取權管理,您應具備 storage.objects.create 權限來寫入物件到值區,並具備 storage.objects.get 權限來從值區讀取物件。請參閱使用身分與存取權管理權限一文中的操作說明,瞭解如何取得具備這些權限的角色,例如 roles/storage.objectAdmin

    • 如果您使用 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 Keys」(Cloud Key Management Service 金鑰) 瀏覽器。
    開啟 Cloud KMS 金鑰瀏覽器
  2. 按一下包含要使用金鑰的金鑰環名稱。

  3. 選取要使用金鑰的核取方塊。

    右邊窗格的「Permissions」(權限) 分頁隨即顯示。

  4. 在「Add members」(新增成員) 對話框中,指定授予 Cloud Storage 服務帳戶存取權的電子郵件地址。

  5. 在「Select a role」(選取角色) 下拉式清單中,選取 [Cloud KMS CryptoKey Encrypter/Decrypter] (Cloud KMS 加密編譯金鑰加密者/解密者)。

  6. 按一下 [Add] (新增)。

gsutil

使用 gsutil kms authorize 指令為值區相關服務帳戶提供利用 Cloud KMS 金鑰加密或解密物件的權限:

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

其中:

  • [PROJECT_STORING_OBJECTS] 是包含您要加密或解密之物件的專案 ID。例如:my-pet-project
  • [KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

如要移除授予的權限,您必須使用 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 參考說明文件

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/iam"
	cloudkms "cloud.google.com/go/kms/apiv1"
	kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

// addMemberRingPolicy adds a new member to a specified IAM role for the key ring.
func addMemberRingPolicy(w io.Writer, keyRingName, member string, role iam.RoleName) error {
	// keyRingName := "projects/PROJECT_ID/locations/global/keyRings/RING_ID"
	// member := "user@gmail.com"
	// role := iam.Viewer
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("cloudkms.NewKeyManagementClient: %v", err)
	}

	// Get the KeyRing.
	keyRingObj, err := client.GetKeyRing(ctx, &kmspb.GetKeyRingRequest{Name: keyRingName})
	if err != nil {
		return fmt.Errorf("GetKeyRing: %v", err)
	}
	// Get IAM Policy.
	handle := client.KeyRingIAM(keyRingObj)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("Policy: %v", err)
	}
	// Add Member.
	policy.Add(member, role)
	if err = handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("SetPolicy: %v", err)
	}
	fmt.Fprintf(w, "Added member %s to keyring policy.", member)
	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."""

    from google.cloud import kms_v1

    # 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 檔案:

    {
      "policy": {
        "bindings": {
          "role": "roles/cloudkms.cryptoKeyEncrypterDecrypter",
          "members": "[SERVICE_ACCOUNT_EMAIL_ADDRESS]"
        },
      }
    }

    其中,[SERVICE_ACCOUNT_EMAIL_ADDRESS] 是與您的服務帳戶相關聯的電子郵件地址。例如:service-7550275089395@my-pet-project.iam.gserviceaccount.com

  3. 使用 cURL 來透過 POST setIamPolicy 要求呼叫 Cloud KMS API:

    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"

    其中:

    • [JSON_FILE_NAME] 是您在步驟 2 建立的檔案名稱。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

XML API

XML API 無法用於將 Cloud KMS 指派到服務帳戶。請改用 gsutil 等其他 Cloud Storage 工具。

使用預設的加密金鑰

新增或變更值區的預設金鑰

如要在寫入物件到值區時,新增或變更依預設使用的 Cloud KMS 金鑰:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中按一下您要使用的值區。

  3. 按一下頁面頂端的 [Edit bucket] (編輯值區)

  4. 在「Edit Bucket」(編輯值區) 頁面中,點選可展開的 [Show advanced settings] (顯示進階設定)。

  5. 如果該值區目前並未使用 Cloud KMS 金鑰,請選取 [Customer-managed key] (客戶管理的金鑰) 圓形按鈕。

  6. 在與客戶代管金鑰相關的下拉式選單中,選取其中一個可用的金鑰。

  7. 按一下 [Save] (儲存)

gsutil

使用 gsutil kms encryption 指令:

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

其中:

  • [KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key
  • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

如果成功,回應如下所示:

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 檔案:

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

    其中,[KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

  3. 使用 cURL 來透過 PATCH 值區要求呼叫 JSON API:

    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"

    其中:

    • [JSON_FILE_NAME] 是您在步驟 2 建立的檔案。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .xml 檔案:

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

    其中,[KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

  3. 使用 cURL 來透過 PUT 值區要求和 encryption 查詢字串參數呼叫 XML API:

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

    其中:

    • [XML_FILE_NAME] 是您在步驟 2 建立的檔案。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

查看值區的預設金鑰

如要查看目前為值區預設的 Cloud KMS 金鑰:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中按一下您要使用的值區。

  3. 在值區詳細資料頁面中,點選 [Overview] (總覽) 分頁標籤。

  4. 目前值區預設的金鑰會出現在「Encryption key」(加密金鑰) 欄位。

gsutil

使用 gsutil kms encryption 指令:

gsutil kms encryption gs://[BUCKET_NAME]

其中,[BUCKET_NAME] 是您要查看其金鑰的值區名稱。例如:my-bucket

如果成功,回應如下所示:

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

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 使用 cURL 來透過包含所需 fieldsGET 值區要求呼叫 JSON API:

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

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是您要查看其金鑰的值區名稱。例如:my-bucket

    回應類似下列範例:

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

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 使用 cURL 來透過包含 encryption 查詢參數的 GET 值區要求呼叫 XML API:

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

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是您要查看其金鑰的值區名稱。例如:my-bucket

    回應類似下列範例:

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

從值區移除預設金鑰

如要移除值區上任何預設的 Cloud KMS 金鑰組:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中按一下您要使用的值區。

  3. 按一下頁面頂端的 [Edit bucket] (編輯值區)

  4. 在「Edit Bucket」(編輯值區) 頁面中,點選可展開的 [Show advanced settings] (顯示進階設定)。

  5. 選取 [Google-managed key] (Google 管理的金鑰) 圓形按鈕。

  6. 按一下 [Save] (儲存)

gsutil

使用 gsutil kms encryption 指令:

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

其中 [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

如果成功,回應如下所示:

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 值區要求呼叫 JSON API:

    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"

    其中:

    • [JSON_FILE_NAME] 是您在步驟 2 建立的檔案。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .xml 檔案:

    <EncryptionConfiguration></EncryptionConfiguration>
  3. 使用 cURL 來透過 PUT 值區要求和 encryption 查詢字串參數呼叫 XML API:

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

    其中:

    • [XML_FILE_NAME] 是您在步驟 2 建立的檔案。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

使用 Cloud KMS 金鑰加密物件

您可以使用 Cloud KMS 金鑰加密個別物件。如果您要使用值區預設金鑰組的另一個金鑰,或者值區上沒有預設金鑰組時,這種方式即可派上用場。

主控台

您無法使用 GCP Console 來加密個別物件。請改用 gsutil 或用戶端程式庫。

gsutil

  1. 將下列選項新增至 .boto 設定檔[GSUtil] 區段:

    encryption_key = [KEY_RESOURCE]

    其中,[KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

  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 物件要求呼叫 JSON API:

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

    其中:

    • [OBJECT] 是您要上傳的物件路徑。例如:Desktop/dog.png
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [OBJECT_CONTENT_TYPE] 是物件的內容類型。例如:image/png
    • [BUCKET_NAME] 是您要上傳的物件值區名稱。例如:my-bucket
    • [OBJECT_NAME] 是您要上傳的物件名稱。例如:pets/dog.png
    • [KEY_RESOURCE]Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 將物件的資料新增至要求主體。

  3. 使用 cURL 來透過 PUT 物件要求呼叫 XML API:

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

    其中:

    • [OBJECT] 是您要上傳的物件路徑。例如:Desktop/dog.png
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [OBJECT_CONTENT_TYPE] 是物件的內容類型。例如:image/png
    • [BUCKET_NAME] 是您要上傳的物件值區名稱。例如:my-bucket
    • [OBJECT_NAME] 是您要上傳的物件名稱。例如:pets/dog.png
    • [KEY_RESOURCE] 是您的 Cloud KMS 金鑰資源。例如:projects/my-pet-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key

找出用來加密物件的金鑰

如要找出用來加密物件的 Cloud KMS 金鑰名稱:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 瀏覽至相關值區中要使用的物件。

  3. 在「Encryption」(加密) 資料欄中,將滑鼠游標移到想要的物件項目上。

    金鑰名稱會如以下格式顯示:

    [LOCATION]/[KEY_RING_NAME]/[KEY_NAME]/[KEY_VERSION]

gsutil

使用 gsutil stat 指令:

gsutil stat gs://[BUCKET_NAME]/[OBJECT_NAME]

其中:

  • [BUCKET_NAME] 是包含加密物件的值區名稱。例如:my-bucket
  • [OBJECT_NAME] 是加密物件名稱。例如:pets/dog.png

如果成功,回應會包含金鑰名稱:

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

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 使用 cURL 來透過 GET 物件要求呼叫 JSON API:

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

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是包含加密物件的值區名稱。例如:my-bucket
    • [OBJECT_NAME] 是加密物件名稱。例如:pets/dog.png

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 使用 cURL 來透過 GET 物件要求呼叫 XML API:

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

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [BUCKET_NAME] 是包含加密物件的值區名稱。例如:my-bucket
    • [OBJECT_NAME] 是加密物件名稱。例如:pets/dog.png

加密物件

只要相關服務具有客戶代管加密金鑰的存取權,系統就會針對使用該金鑰加密的物件,自動執行解密。詳情請參閱具有客戶代管加密金鑰的服務帳戶說明。

後續步驟