建立金鑰環

本頁說明如何在 Cloud KMS 中建立金鑰環。金鑰環是 Cloud KMS 金鑰和金鑰版本的根資源。每個金鑰環都位於特定位置。如要進一步瞭解 Cloud KMS 資源,請參閱「Cloud KMS 資源」。

事前準備

完成本頁面上的工作前,您需要下列項目:

  • Trusted Cloud 專案資源,用於存放 Cloud KMS 資源。這個專案稱為「金鑰專案」。建議主要專案不要包含任何其他Trusted Cloud 資源。在金鑰專案中啟用 Cloud KMS API。

    啟用 API

  • 您要在其中建立金鑰環的位置名稱。選擇鄰近其他資源的位置,並支援所選保護等級。如要查看可用的位置和支援的保護等級,請參閱 Cloud KMS 位置

必要的角色

如要取得建立金鑰環所需的權限,請要求管理員在專案或父項資源中,授予您 Cloud KMS 管理員 (roles/cloudkms.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色具備建立金鑰環所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要建立金鑰環,您必須具備下列權限:

  • cloudkms.keyRings.create
  • cloudkms.keyRings.get
  • cloudkms.keyRings.list
  • cloudkms.locations.get
  • cloudkms.locations.list
  • resourcemanager.projects.get

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

建立金鑰環

請按照下列步驟為新金鑰建立金鑰環。如要改用現有金鑰環,可以建立金鑰

控制台

  1. 前往 Trusted Cloud 控制台的「Key Management」頁面。

    前往「金鑰管理」

  2. 按一下 [Create key ring] (建立金鑰環)

  3. 在「Key ring name」(金鑰環名稱) 欄位中,輸入金鑰環的名稱。

  4. 針對「Key ring location」(金鑰環位置),選取位置,例如 "us-east1"

  5. 點選「建立」

gcloud

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

  2. 在環境中執行 gcloud kms keyrings create 指令:

    gcloud kms keyrings create KEY_RING \
        --location LOCATION
    

    更改下列內容:

    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。

    如要瞭解所有旗標和可能的值,請使用 --help 旗標執行指令。

  3. C#

    如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Cloud KMS C# SDK

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Kms.V1;
    
    public class CreateKeyRingSample
    {
        public KeyRing CreateKeyRing(
          string projectId = "my-project", string locationId = "us-east1",
          string id = "my-key-ring")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the parent location name.
            LocationName locationName = new LocationName(projectId, locationId);
    
            // Build the key ring.
            KeyRing keyRing = new KeyRing { };
    
            // Call the API.
            KeyRing result = client.CreateKeyRing(locationName, id, keyRing);
    
            // Return the result.
            return result;
        }
    }

    Go

    如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Cloud KMS Go SDK

    import (
    	"context"
    	"fmt"
    	"io"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    )
    
    // createKeyRing creates a new ring to store keys on KMS.
    func createKeyRing(w io.Writer, parent, id string) error {
    	// parent := "projects/PROJECT_ID/locations/global"
    	// id := "my-key-ring"
    
    	// Create the client.
    	ctx := context.Background()
    	client, err := kms.NewKeyManagementClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create kms client: %w", err)
    	}
    	defer client.Close()
    
    	// Build the request.
    	req := &kmspb.CreateKeyRingRequest{
    		Parent:    parent,
    		KeyRingId: id,
    	}
    
    	// Call the API.
    	result, err := client.CreateKeyRing(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key ring: %w", err)
    	}
    	fmt.Fprintf(w, "Created key ring: %s\n", result.Name)
    	return nil
    }
    

    Java

    如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Cloud KMS Java SDK

    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.KeyRing;
    import com.google.cloud.kms.v1.LocationName;
    import java.io.IOException;
    
    public class CreateKeyRing {
    
      public void createKeyRing() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String id = "my-asymmetric-signing-key";
        createKeyRing(projectId, locationId, id);
      }
    
      // Create a new key ring.
      public void createKeyRing(String projectId, String locationId, String id) throws IOException {
        // Initialize client that will be used to send requests. This client only
        // needs to be created once, and can be reused for multiple requests. After
        // completing all of your requests, call the "close" method on the client to
        // safely clean up any remaining background resources.
        try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
          // Build the parent name from the project and location.
          LocationName locationName = LocationName.of(projectId, locationId);
    
          // Build the key ring to create.
          KeyRing keyRing = KeyRing.newBuilder().build();
    
          // Create the key ring.
          KeyRing createdKeyRing = client.createKeyRing(locationName, id, keyRing);
          System.out.printf("Created key ring %s%n", createdKeyRing.getName());
        }
      }
    }

    Node.js

    如要執行這段程式碼,請先設定 Node.js 開發環境,然後安裝 Cloud KMS Node.js SDK

    //
    // TODO(developer): Uncomment these variables before running the sample.
    //
    // const projectId = 'my-project';
    // const locationId = 'us-east1';
    // const id = 'my-key-ring';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the parent location name
    const locationName = client.locationPath(projectId, locationId);
    
    async function createKeyRing() {
      const [keyRing] = await client.createKeyRing({
        parent: locationName,
        keyRingId: id,
      });
    
      console.log(`Created key ring: ${keyRing.name}`);
      return keyRing;
    }
    
    return createKeyRing();

    PHP

    如要執行這段程式碼,請先瞭解如何在 Trusted Cloud上使用 PHP,並安裝 Cloud KMS PHP SDK

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\CreateKeyRingRequest;
    use Google\Cloud\Kms\V1\KeyRing;
    
    function create_key_ring(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $id = 'my-key-ring'
    ): KeyRing {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent location name.
        $locationName = $client->locationName($projectId, $locationId);
    
        // Build the key ring.
        $keyRing = new KeyRing();
    
        // Call the API.
        $createKeyRingRequest = (new CreateKeyRingRequest())
            ->setParent($locationName)
            ->setKeyRingId($id)
            ->setKeyRing($keyRing);
        $createdKeyRing = $client->createKeyRing($createKeyRingRequest);
        printf('Created key ring: %s' . PHP_EOL, $createdKeyRing->getName());
    
        return $createdKeyRing;
    }

    Python

    如要執行這段程式碼,請先設定 Python 開發環境,然後安裝 Cloud KMS Python SDK

    from google.cloud import kms
    
    
    def create_key_ring(
        project_id: str, location_id: str, key_ring_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new key ring in Cloud KMS
    
        Args:
            project_id (string): Google Cloud project ID (e.g. 'my-project').
            location_id (string): Cloud KMS location (e.g. 'us-east1').
            key_ring_id (string): ID of the key ring to create (e.g. 'my-key-ring').
    
        Returns:
            KeyRing: Cloud KMS key ring.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent location name.
        location_name = f"projects/{project_id}/locations/{location_id}"
    
        # Build the key ring.
        key_ring = {}
    
        # Call the API.
        created_key_ring = client.create_key_ring(
            request={
                "parent": location_name,
                "key_ring_id": key_ring_id,
                "key_ring": key_ring,
            }
        )
        print(f"Created key ring: {created_key_ring.name}")
        return created_key_ring
    
    

    Ruby

    如要執行這段程式碼,請先設定 Ruby 開發環境,然後安裝 Cloud KMS Ruby SDK

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # id = "my-key-ring"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent location name.
    location_name = client.location_path project: project_id, location: location_id
    
    # Build the key ring.
    key_ring = {}
    
    # Call the API.
    created_key_ring = client.create_key_ring parent: location_name, key_ring_id: id, key_ring: key_ring
    puts "Created key ring: #{created_key_ring.name}"

    API

    這些範例使用 curl 做為 HTTP 用戶端,示範如何使用 API。如要進一步瞭解存取權控管,請參閱「存取 Cloud KMS API」一文。

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings?key_ring_id=KEY_RING" \
        --request "POST" \
        --header "authorization: Bearer TOKEN"
    

    更改下列內容:

    • PROJECT_ID:包含金鑰環的專案 ID。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。

    詳情請參閱 KeyRing.create API 說明文件

後續步驟