建立金鑰

本頁說明如何在 Cloud KMS 中建立金鑰。金鑰可以是對稱或非對稱加密金鑰、非對稱簽署金鑰,或是 MAC 簽署金鑰。

建立金鑰時,請將金鑰新增至特定 Cloud KMS 位置的金鑰環。您可以建立新的金鑰環,或使用現有的金鑰環。 在這個頁面中,您會產生新的 Cloud KMS 或 Cloud HSM 金鑰,並將其新增至現有金鑰環。 如要建立 Cloud EKM 金鑰,請參閱「建立外部金鑰」。如要匯入 Cloud KMS 或 Cloud HSM 金鑰,請參閱「匯入金鑰」。

事前準備

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

  1. Google Cloud 專案資源,用於存放 Cloud KMS 資源。建議您為 Cloud KMS 資源使用獨立專案,不要包含任何其他 Google Cloud 資源。
  2. 您要在哪個金鑰環中建立金鑰,以及該金鑰環的名稱和位置。 選擇與其他資源相近位置的金鑰環,並支援所選保護等級。 如要查看可用的位置和支援的保護等級,請參閱 Cloud KMS 位置。 如要建立金鑰環,請參閱「建立金鑰環」。
  3. 選用:如要使用 gcloud CLI,請準備環境。

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    必要的角色

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

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

    所需權限

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

    • cloudkms.cryptoKeys.create
    • cloudkms.cryptoKeys.get
    • cloudkms.cryptoKeys.list
    • cloudkms.cryptoKeyVersions.create
    • cloudkms.cryptoKeyVersions.get
    • cloudkms.cryptoKeyVersions.list
    • cloudkms.keyRings.get
    • cloudkms.keyRings.list
    • cloudkms.locations.get
    • cloudkms.locations.list
    • resourcemanager.projects.get
    • 如要擷取公開金鑰,請按照下列步驟操作: cloudkms.cryptoKeyVersions.viewPublicKey

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

    建立對稱式加密金鑰

    控制台

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

      前往「金鑰管理」

    2. 找出您要在哪個金鑰環中建立金鑰,然後按一下該金鑰環名稱。

    3. 按一下 [Create key] (建立金鑰)

    4. 在「金鑰名稱」中,輸入金鑰的名稱。

    5. 在「Protection level」(防護等級) 中,選取「Software」(軟體) 或「HSM」

    6. 在「Key material」(金鑰內容) 中,選取「Generated key」(產生的金鑰)

    7. 針對「Purpose」(目的),選取 Symmetric encrypt/decrypt

    8. 接受「Rotation period」(輪替週期) 和「Starting on」(開始日期) 的預設值。

    9. 點選「建立」

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "encryption" \
        --protection-level "PROTECTION_LEVEL"
    

    更改下列內容:

    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • PROTECTION_LEVEL:金鑰要使用的防護等級,例如 softwarehsm。您可以省略 software 鍵的 --protection-level 標記。

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

    C#

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

    
    using Google.Cloud.Kms.V1;
    
    public class CreateKeySymmetricEncryptDecryptSample
    {
        public CryptoKey CreateKeySymmetricEncryptDecrypt(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-symmetric-encryption-key")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the parent key ring name.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
    
            // Build the key.
            CryptoKey key = new CryptoKey
            {
                Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // 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"
    )
    
    // createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
    // on Cloud KMS.
    func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-symmetric-encryption-key"
    
    	// 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.CreateCryptoKeyRequest{
    		Parent:      parent,
    		CryptoKeyId: id,
    		CryptoKey: &kmspb.CryptoKey{
    			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
    			},
    		},
    	}
    
    	// Call the API.
    	result, err := client.CreateCryptoKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key: %w", err)
    	}
    	fmt.Fprintf(w, "Created key: %s\n", result.Name)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKey;
    import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
    import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
    import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.KeyRingName;
    import java.io.IOException;
    
    public class CreateKeySymmetricEncryptDecrypt {
    
      public void createKeySymmetricEncryptDecrypt() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String id = "my-key";
        createKeySymmetricEncryptDecrypt(projectId, locationId, keyRingId, id);
      }
    
      // Create a new key that is used for symmetric encryption and decryption.
      public void createKeySymmetricEncryptDecrypt(
          String projectId, String locationId, String keyRingId, 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, location, and key ring.
          KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
    
          // Build the symmetric key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created symmetric key %s%n", createdKey.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 keyRingId = 'my-key-ring';
    // const id = 'my-symmetric-encryption-key';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the parent key ring name
    const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
    
    async function createKeySymmetricEncryptDecrypt() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ENCRYPT_DECRYPT',
          versionTemplate: {
            algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
          },
        },
      });
    
      console.log(`Created symmetric key: ${key.name}`);
      return key;
    }
    
    return createKeySymmetricEncryptDecrypt();

    PHP

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

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
    use Google\Cloud\Kms\V1\CryptoKey;
    use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
    use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
    use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
    
    function create_key_symmetric_encrypt_decrypt(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-symmetric-key'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

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

    from google.cloud import kms
    
    
    def create_key_symmetric_encrypt_decrypt(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new symmetric encryption/decryption key 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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to create (e.g. 'my-symmetric-key').
    
        Returns:
            CryptoKey: Cloud KMS key.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent key ring name.
        key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    
        # Build the key.
        purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
        }
    
        # Call the API.
        created_key = client.create_crypto_key(
            request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
        )
        print(f"Created symmetric key: {created_key.name}")
        return created_key
    
    

    Ruby

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

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # key_ring_id = "my-key-ring"
    # id          = "my-symmetric-key"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent key ring name.
    key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
    
    # Build the key.
    key = {
      purpose:          :ENCRYPT_DECRYPT,
      version_template: {
        algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created symmetric key: #{created_key.name}"

    API

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

    如要建立金鑰,請使用 CryptoKey.create 方法:

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'
    

    更改下列內容:

    • PROJECT_ID:包含金鑰環的專案 ID。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • KEY_NAME:金鑰名稱。
    • PROTECTION_LEVEL:金鑰的防護等級,例如 SOFTWAREHSM
    • ALGORITHM:HMAC 簽署演算法,例如 HMAC_SHA256。如要查看所有支援的 HMAC 演算法,請參閱 HMAC 簽署演算法

    建立具有自訂自動輪替功能的對稱式加密金鑰

    建立金鑰時,您可以指定輪替週期,也就是自動建立新金鑰版本的間隔時間。您也可以獨立指定下一個輪替時間,讓下一次輪替發生在目前時間的一個輪替週期之前或之後。

    控制台

    使用 Google Cloud 控制台建立金鑰時,Cloud KMS 會自動設定輪替週期和下一個輪替時間。你可以選擇使用預設值,或指定其他值。

    如要在建立金鑰時指定其他輪替週期和開始時間,請在執行下列操作「之後」才點選「建立」按鈕:

    1. 在「金鑰輪替週期」部分,選取所需選項。

    2. 在「開始於」中,選取您希望系統首次自動輪播廣告的日期。您可以將「開始時間」保留為預設值,這樣系統會在您建立金鑰後,經過一個金鑰輪替週期時,開始第一次自動輪替。

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "encryption" \
        --rotation-period ROTATION_PERIOD \
        --next-rotation-time NEXT_ROTATION_TIME
    

    更改下列內容:

    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • ROTATION_PERIOD:輪替金鑰的間隔,例如 30d 表示每 30 天輪替一次金鑰。輪替週期至少須為 1 天,最多為 100 年。詳情請參閱「CryptoKey.rotationPeriod」。
    • NEXT_ROTATION_TIME:完成第一次輪替的時間戳記,例如 2023-01-01T01:02:03。您可以省略 --next-rotation-time,將首次輪替排定在執行指令後的一個輪替週期。詳情請參閱 CryptoKey.nextRotationTime

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

    C#

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

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    using System;
    
    public class CreateKeyRotationScheduleSample
    {
        public CryptoKey CreateKeyRotationSchedule(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-key-with-rotation-schedule")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the parent key ring name.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
    
            // Build the key.
            CryptoKey key = new CryptoKey
            {
                Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
                },
    
                // Rotate the key every 30 days.
                RotationPeriod = new Duration
                {
                    Seconds = 60 * 60 * 24 * 30, // 30 days
                },
    
                // Start the first rotation in 24 hours.
                NextRotationTime = new Timestamp
                {
                    Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

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

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    	"google.golang.org/protobuf/types/known/durationpb"
    	"google.golang.org/protobuf/types/known/timestamppb"
    )
    
    // createKeyRotationSchedule creates a key with a rotation schedule.
    func createKeyRotationSchedule(w io.Writer, parent, id string) error {
    	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-key-with-rotation-schedule"
    
    	// 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.CreateCryptoKeyRequest{
    		Parent:      parent,
    		CryptoKeyId: id,
    		CryptoKey: &kmspb.CryptoKey{
    			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
    			},
    
    			// Rotate the key every 30 days
    			RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
    				RotationPeriod: &durationpb.Duration{
    					Seconds: int64(60 * 60 * 24 * 30), // 30 days
    				},
    			},
    
    			// Start the first rotation in 24 hours
    			NextRotationTime: &timestamppb.Timestamp{
    				Seconds: time.Now().Add(24 * time.Hour).Unix(),
    			},
    		},
    	}
    
    	// Call the API.
    	result, err := client.CreateCryptoKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key: %w", err)
    	}
    	fmt.Fprintf(w, "Created key: %s\n", result.Name)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKey;
    import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
    import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
    import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.KeyRingName;
    import com.google.protobuf.Duration;
    import com.google.protobuf.Timestamp;
    import java.io.IOException;
    import java.time.temporal.ChronoUnit;
    
    public class CreateKeyRotationSchedule {
    
      public void createKeyRotationSchedule() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String id = "my-key";
        createKeyRotationSchedule(projectId, locationId, keyRingId, id);
      }
    
      // Create a new key that automatically rotates on a schedule.
      public void createKeyRotationSchedule(
          String projectId, String locationId, String keyRingId, 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, location, and key ring.
          KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
    
          // Calculate the date 24 hours from now (this is used below).
          long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();
    
          // Build the key to create with a rotation schedule.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
    
                  // Rotate every 30 days.
                  .setRotationPeriod(
                      Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))
    
                  // Start the first rotation in 24 hours.
                  .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created key with rotation schedule %s%n", createdKey.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 keyRingId = 'my-key-ring';
    // const id = 'my-rotating-encryption-key';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the parent key ring name
    const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
    
    async function createKeyRotationSchedule() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ENCRYPT_DECRYPT',
          versionTemplate: {
            algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
          },
    
          // Rotate the key every 30 days.
          rotationPeriod: {
            seconds: 60 * 60 * 24 * 30,
          },
    
          // Start the first rotation in 24 hours.
          nextRotationTime: {
            seconds: new Date().getTime() / 1000 + 60 * 60 * 24,
          },
        },
      });
    
      console.log(`Created rotating key: ${key.name}`);
      return key;
    }
    
    return createKeyRotationSchedule();

    PHP

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

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
    use Google\Cloud\Kms\V1\CryptoKey;
    use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
    use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
    use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
    use Google\Protobuf\Duration;
    use Google\Protobuf\Timestamp;
    
    function create_key_rotation_schedule(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-key-with-rotation-schedule'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION))
    
            // Rotate the key every 30 days.
            ->setRotationPeriod((new Duration())
                ->setSeconds(60 * 60 * 24 * 30)
            )
    
            // Start the first rotation in 24 hours.
            ->setNextRotationTime((new Timestamp())
                ->setSeconds(time() + 60 * 60 * 24)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created key with rotation: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

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

    import time
    
    from google.cloud import kms
    
    
    def create_key_rotation_schedule(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new key in Cloud KMS that automatically rotates.
    
        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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to create (e.g. 'my-rotating-key').
    
        Returns:
            CryptoKey: Cloud KMS key.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent key ring name.
        key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    
        # Build the key.
        purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Rotate the key every 30 days.
            "rotation_period": {"seconds": 60 * 60 * 24 * 30},
            # Start the first rotation in 24 hours.
            "next_rotation_time": {"seconds": int(time.time()) + 60 * 60 * 24},
        }
    
        # Call the API.
        created_key = client.create_crypto_key(
            request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
        )
        print(f"Created labeled key: {created_key.name}")
        return created_key
    
    

    Ruby

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

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # key_ring_id = "my-key-ring"
    # id          = "my-key-with-rotation"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent key ring name.
    key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
    
    # Build the key.
    key = {
      purpose:            :ENCRYPT_DECRYPT,
      version_template:   {
        algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
      },
    
      # Rotate the key every 30 days.
      rotation_period:    {
        seconds: 60 * 60 * 24 * 30
      },
    
      # Start the first rotation in 24 hours.
      next_rotation_time: {
        seconds: (Time.now + (60 * 60 * 24)).to_i
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created rotating key: #{created_key.name}"

    API

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

    如要建立金鑰,請使用 CryptoKey.create 方法:

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --data '{"purpose": "PURPOSE", "rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'
    

    更改下列內容:

    • PURPOSE:金鑰的用途
    • ROTATION_PERIOD:輪替金鑰的間隔,例如 30d 表示每 30 天輪替一次金鑰。輪替週期至少須為 1 天,最多為 100 年。詳情請參閱「CryptoKey.rotationPeriod」。
    • NEXT_ROTATION_TIME:完成第一次輪替的時間戳記,例如 2023-01-01T01:02:03。詳情請參閱 CryptoKey.nextRotationTime

    設定「已安排刪除」狀態的持續時間

    根據預設,Cloud KMS 中的金鑰版本會處於「已安排刪除」狀態 (DESTROY_SCHEDULED) 30 天,然後才會遭到刪除。「已安排刪除」狀態有時也稱為「軟刪除狀態」。您可以設定金鑰版本處於這個狀態的時間長度,但須遵守下列限制:

    • 您只能在建立金鑰時設定時間長度。
    • 指定金鑰的有效時間後,就無法變更。
    • 這項期限會套用至日後建立的所有金鑰版本。
    • 所有金鑰的最短時間為 24 小時,但僅供匯入的金鑰例外,最短時間為 0。
    • 最長 120 天。
    • 預設時間為 30 天。

    貴機構可能已透過機構政策定義銷毀排程的最低時間值。詳情請參閱「控管金鑰銷毀作業」。

    如要建立金鑰,並為「預定銷毀」狀態設定自訂時間長度,請按照下列步驟操作:

    控制台

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

      前往「金鑰管理」

    2. 找出您要在哪個金鑰環中建立金鑰,然後按一下該金鑰環名稱。

    3. 按一下 [Create key] (建立金鑰)

    4. 設定應用程式的金鑰。

    5. 按一下「其他設定」

    6. 在「『已安排刪除』狀態的持續時間」中,選擇金鑰在安排刪除後,永久刪除前的天數。

    7. 按一下 [Create key] (建立金鑰)

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose PURPOSE \
        --destroy-scheduled-duration DURATION
    

    更改下列內容:

    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • PURPOSE:金鑰用途,例如 encryption
    • DURATION:金鑰在永久刪除前,維持在「已安排刪除」狀態的時間長度。

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

    除非有特定應用程式或法規要求,否則建議所有金鑰都使用預設的 30 天期限。

    建立非對稱式金鑰

    以下各節說明如何建立非對稱金鑰。

    建立非對稱式解密金鑰

    請按照下列步驟,在指定的金鑰環和位置建立非對稱式解密金鑰。您可以調整這些範例,指定不同的保護層級或演算法。如需更多資訊和替代值,請參閱「演算法」和「保護等級」。

    首次建立金鑰時,初始金鑰版本的狀態為「尚待產生」。狀態變更為「已啟用」後,即可使用金鑰。如要進一步瞭解金鑰版本狀態,請參閱「金鑰版本狀態」一文。

    控制台

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

      前往「金鑰管理」

    2. 找出您要在哪個金鑰環中建立金鑰,然後按一下該金鑰環名稱。

    3. 按一下 [Create key] (建立金鑰)

    4. 在「金鑰名稱」中,輸入金鑰的名稱。

    5. 在「防護等級」中,選取「軟體」或「HSM」

    6. 在「Key material」(金鑰內容) 中,選取「Generated key」(產生的金鑰)

    7. 針對「Purpose」(目的),選取「Asymmetric decrypt」(非對稱式解密)。

    8. 在「Algorithm」部分,選取「3072 bit RSA - OAEP Padding - SHA256 Digest」。 您可以在日後的金鑰版本中變更這個值。

    9. 點選「建立」

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "asymmetric-encryption" \
        --default-algorithm "ALGORITHM"
    

    更改下列內容:

    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • ALGORITHM:用於金鑰的演算法,例如 rsa-decrypt-oaep-3072-sha256。如需支援的非對稱式加密演算法清單,請參閱「非對稱式加密演算法」。

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

    C#

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

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    
    public class CreateKeyAsymmetricDecryptSample
    {
        public CryptoKey CreateKeyAsymmetricDecrypt(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-asymmetric-encrypt-key")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the parent key ring name.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
    
            // Build the key.
            CryptoKey key = new CryptoKey
            {
                Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricDecrypt,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaDecryptOaep2048Sha256,
                },
    
                // Optional: customize how long key versions should be kept before destroying.
                DestroyScheduledDuration = new Duration
                {
                    Seconds = 24 * 60 * 60,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

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

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    	"google.golang.org/protobuf/types/known/durationpb"
    )
    
    // createKeyAsymmetricDecrypt creates a new asymmetric RSA encrypt/decrypt key
    // pair where the private key is stored in Cloud KMS.
    func createKeyAsymmetricDecrypt(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-asymmetric-encryption-key"
    
    	// 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.CreateCryptoKeyRequest{
    		Parent:      parent,
    		CryptoKeyId: id,
    		CryptoKey: &kmspb.CryptoKey{
    			Purpose: kmspb.CryptoKey_ASYMMETRIC_DECRYPT,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_RSA_DECRYPT_OAEP_2048_SHA256,
    			},
    
    			// Optional: customize how long key versions should be kept before destroying.
    			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
    		},
    	}
    
    	// Call the API.
    	result, err := client.CreateCryptoKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key: %w", err)
    	}
    	fmt.Fprintf(w, "Created key: %s\n", result.Name)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKey;
    import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
    import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
    import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.KeyRingName;
    import com.google.protobuf.Duration;
    import java.io.IOException;
    
    public class CreateKeyAsymmetricDecrypt {
    
      public void createKeyAsymmetricDecrypt() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String id = "my-asymmetric-decryption-key";
        createKeyAsymmetricDecrypt(projectId, locationId, keyRingId, id);
      }
    
      // Create a new asymmetric key for the purpose of encrypting and decrypting
      // data.
      public void createKeyAsymmetricDecrypt(
          String projectId, String locationId, String keyRingId, 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, location, and key ring.
          KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
    
          // Build the asymmetric key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ASYMMETRIC_DECRYPT)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256))
    
                  // Optional: customize how long key versions should be kept before destroying.
                  .setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created asymmetric key %s%n", createdKey.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 keyRingId = 'my-key-ring';
    // const id = 'my-asymmetric-decrypt-key';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the parent key ring name
    const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
    
    async function createKeyAsymmetricDecrypt() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ASYMMETRIC_DECRYPT',
          versionTemplate: {
            algorithm: 'RSA_DECRYPT_OAEP_2048_SHA256',
          },
    
          // Optional: customize how long key versions should be kept before
          // destroying.
          destroyScheduledDuration: {seconds: 60 * 60 * 24},
        },
      });
    
      console.log(`Created asymmetric key: ${key.name}`);
      return key;
    }
    
    return createKeyAsymmetricDecrypt();

    PHP

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

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
    use Google\Cloud\Kms\V1\CryptoKey;
    use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
    use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
    use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
    use Google\Protobuf\Duration;
    
    function create_key_asymmetric_decrypt(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-asymmetric-decrypt-key'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::ASYMMETRIC_DECRYPT)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_DECRYPT_OAEP_2048_SHA256)
            )
    
            // Optional: customize how long key versions should be kept before destroying.
            ->setDestroyScheduledDuration((new Duration())
                ->setSeconds(24 * 60 * 60)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created asymmetric decryption key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

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

    import datetime
    
    # Import the client library.
    from google.cloud import kms
    from google.protobuf import duration_pb2  # type: ignore
    
    
    def create_key_asymmetric_decrypt(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new asymmetric decryption key 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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to create (e.g. 'my-asymmetric-decrypt-key').
    
        Returns:
            CryptoKey: Cloud KMS key.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent key ring name.
        key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    
        # Build the key.
        purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Optional: customize how long key versions should be kept before
            # destroying.
            "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
                datetime.timedelta(days=1)
            ),
        }
    
        # Call the API.
        created_key = client.create_crypto_key(
            request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
        )
        print(f"Created asymmetric decrypt key: {created_key.name}")
        return created_key
    
    

    Ruby

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

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # key_ring_id = "my-key-ring"
    # id          = "my-asymmetric-decrypt-key"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent key ring name.
    key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
    
    # Build the key.
    key = {
      purpose:          :ASYMMETRIC_DECRYPT,
      version_template: {
        algorithm: :RSA_DECRYPT_OAEP_2048_SHA256
      },
    
      # Optional: customize how long key versions should be kept before destroying.
      destroy_scheduled_duration: {
        seconds: 24 * 60 * 60
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created asymmetric decryption key: #{created_key.name}"

    API

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

    呼叫 CryptoKey.create 建立非對稱式解密金鑰。

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --data '{"purpose": "ASYMMETRIC_DECRYPT", "versionTemplate": {"algorithm": "ALGORITHM"}}'
    

    更改下列內容:

    • PROJECT_ID:包含金鑰環的專案 ID。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • KEY_NAME:金鑰名稱。
    • ALGORITHM:用於金鑰的演算法,例如 RSA_DECRYPT_OAEP_3072_SHA256。如需支援的非對稱式加密演算法清單,請參閱「非對稱式加密演算法」。

    建立非對稱式簽署金鑰

    請按照下列步驟,在指定的金鑰環和位置建立非對稱式簽署金鑰。您可以調整這些範例,指定不同的保護層級或演算法。如需更多資訊和替代值,請參閱「演算法」和「保護等級」。

    首次建立金鑰時,初始金鑰版本的狀態為「尚待產生」。狀態變更為「已啟用」後,即可使用金鑰。如要進一步瞭解金鑰版本狀態,請參閱「金鑰版本狀態」一文。

    控制台

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

      前往「金鑰管理」

    2. 找出您要在哪個金鑰環中建立金鑰,然後按一下該金鑰環名稱。

    3. 按一下 [Create key] (建立金鑰)

    4. 在「金鑰名稱」中,輸入金鑰的名稱。

    5. 在「防護等級」中,選取「軟體」或「HSM」

    6. 在「Key material」(金鑰內容) 中,選取「Generated key」(產生的金鑰)

    7. 在「Purpose」部分,選取「Asymmetric sign」

    8. 在「演算法」部分,選取「橢圓曲線 P-256 - SHA256 摘要」。您可以在日後金鑰版本中變更這個值。

    9. 點選「建立」

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "asymmetric-signing" \
        --default-algorithm "ALGORITHM"
    

    更改下列內容:

    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • ALGORITHM:用於金鑰的演算法,例如 ec-sign-p256-sha256。如需支援的演算法清單,請參閱「非對稱簽署演算法」。

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

    C#

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

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    
    public class CreateKeyAsymmetricSignSample
    {
        public CryptoKey CreateKeyAsymmetricSign(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-asymmetric-signing-key")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the parent key ring name.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
    
            // Build the key.
            CryptoKey key = new CryptoKey
            {
                Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPkcs12048Sha256,
                },
    
                // Optional: customize how long key versions should be kept before destroying.
                DestroyScheduledDuration = new Duration
                {
                    Seconds = 24 * 60 * 60,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

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

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    	"google.golang.org/protobuf/types/known/durationpb"
    )
    
    // createKeyAsymmetricSign creates a new asymmetric RSA sign/verify key pair
    // where the private key is stored in Cloud KMS.
    func createKeyAsymmetricSign(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-asymmetric-signing-key"
    
    	// 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.CreateCryptoKeyRequest{
    		Parent:      parent,
    		CryptoKeyId: id,
    		CryptoKey: &kmspb.CryptoKey{
    			Purpose: kmspb.CryptoKey_ASYMMETRIC_SIGN,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
    			},
    
    			// Optional: customize how long key versions should be kept before destroying.
    			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
    		},
    	}
    
    	// Call the API.
    	result, err := client.CreateCryptoKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key: %w", err)
    	}
    	fmt.Fprintf(w, "Created key: %s\n", result.Name)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKey;
    import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
    import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
    import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.KeyRingName;
    import com.google.protobuf.Duration;
    import java.io.IOException;
    
    public class CreateKeyAsymmetricSign {
    
      public void createKeyAsymmetricSign() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String id = "my-asymmetric-signing-key";
        createKeyAsymmetricSign(projectId, locationId, keyRingId, id);
      }
    
      // Create a new asymmetric key for the purpose of signing and verifying data.
      public void createKeyAsymmetricSign(
          String projectId, String locationId, String keyRingId, 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, location, and key ring.
          KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
    
          // Build the asymmetric key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256))
    
                  // Optional: customize how long key versions should be kept before destroying.
                  .setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created asymmetric key %s%n", createdKey.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 keyRingId = 'my-key-ring';
    // const id = 'my-asymmetric-sign-key';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the parent key ring name
    const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
    
    async function createKeyAsymmetricSign() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ASYMMETRIC_SIGN',
          versionTemplate: {
            algorithm: 'RSA_SIGN_PKCS1_2048_SHA256',
          },
    
          // Optional: customize how long key versions should be kept before
          // destroying.
          destroyScheduledDuration: {seconds: 60 * 60 * 24},
        },
      });
    
      console.log(`Created asymmetric key: ${key.name}`);
      return key;
    }
    
    return createKeyAsymmetricSign();

    PHP

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

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
    use Google\Cloud\Kms\V1\CryptoKey;
    use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
    use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
    use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
    use Google\Protobuf\Duration;
    
    function create_key_asymmetric_sign(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-asymmetric-signing-key'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::ASYMMETRIC_SIGN)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_SIGN_PKCS1_2048_SHA256)
            )
    
            // Optional: customize how long key versions should be kept before destroying.
            ->setDestroyScheduledDuration((new Duration())
                ->setSeconds(24 * 60 * 60)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created asymmetric signing key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

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

    
    import datetime
    
    # Import the client library.
    from google.cloud import kms
    from google.protobuf import duration_pb2  # type: ignore
    
    
    def create_key_asymmetric_sign(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new asymmetric signing key 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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to create (e.g. 'my-asymmetric-signing-key').
    
        Returns:
            CryptoKey: Cloud KMS key.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent key ring name.
        key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    
        # Build the key.
        purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Optional: customize how long key versions should be kept before
            # destroying.
            "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
                datetime.timedelta(days=1)
            ),
        }
    
        # Call the API.
        created_key = client.create_crypto_key(
            request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
        )
        print(f"Created asymmetric signing key: {created_key.name}")
        return created_key
    
    

    Ruby

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

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # key_ring_id = "my-key-ring"
    # id          = "my-asymmetric-signing-key"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent key ring name.
    key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
    
    # Build the key.
    key = {
      purpose:          :ASYMMETRIC_SIGN,
      version_template: {
        algorithm: :RSA_SIGN_PKCS1_2048_SHA256
      },
    
      # Optional: customize how long key versions should be kept before destroying.
      destroy_scheduled_duration: {
        seconds: 24 * 60 * 60
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created asymmetric signing key: #{created_key.name}"

    API

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

    呼叫 CryptoKey.create 建立非對稱式簽署金鑰。

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --data '{"purpose": "ASYMMETRIC_SIGN", "versionTemplate": {"algorithm": "ALGORITHM"}}'
    

    更改下列內容:

    • PROJECT_ID:包含金鑰環的專案 ID。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • KEY_NAME:金鑰名稱。
    • ALGORITHM:用於金鑰的演算法,例如 EC_SIGN_P256_SHA256。如需支援的演算法清單,請參閱「非對稱簽署演算法」。

    擷取公開金鑰

    建立非對稱金鑰時,Cloud KMS 會建立公開/私密金鑰組。啟用非對稱金鑰後,隨時可以擷取金鑰的公開金鑰。

    公開金鑰採用隱私強化電子郵件 (PEM) 格式。詳情請參閱 RFC 7468一般注意事項主體公開金鑰資訊的文字編碼章節。

    如要下載現有非對稱金鑰版本的公開金鑰,請按照下列步驟操作:

    控制台

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

      前往「金鑰管理」

    2. 按一下包含非對稱金鑰的金鑰環名稱,您要擷取該金鑰的公開金鑰。

    3. 按一下要擷取公開金鑰的金鑰名稱。

    4. 在您要擷取公開金鑰的金鑰版本對應列中,按一下「查看更多」圖示

    5. 按一下「取得公開金鑰」

    6. 提示中會顯示公開金鑰。您可以將公開金鑰複製到剪貼簿,如要下載公開金鑰,請按一下「下載」

    如果沒有看到「取得公開金鑰」選項,請確認下列事項:

    • 金鑰為非對稱金鑰。
    • 金鑰版本已啟用。
    • 您擁有「cloudkms.cryptoKeyVersions.viewPublicKey」權限。

    從 Google Cloud 控制台下載的公開金鑰檔案名稱格式如下:

    KEY_RING-KEY_NAME-KEY_VERSION.pub
    

    檔案名稱的每個部分都以連字號分隔,例如 ringname-keyname-version.pub

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys versions get-public-key KEY_VERSION \
        --key KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --public-key-format PUBLIC_KEY_FORMAT \
        --output-file OUTPUT_FILE_PATH
    

    更改下列內容:

    • KEY_VERSION:金鑰版本號碼。
    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • PUBLIC_KEY_FORMAT:您要匯出公開金鑰的格式。如要使用 PQC 演算法 (預覽版),請使用 nist-pqc。對於所有其他鍵,您可以使用 pem 或省略這個參數。
    • OUTPUT_FILE_PATH:要儲存公開金鑰檔案的路徑,例如 public-key.pub

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

    C#

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

    
    using Google.Cloud.Kms.V1;
    
    public class GetPublicKeySample
    {
        public PublicKey GetPublicKey(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the key version name.
            CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);
    
            // Call the API.
            PublicKey result = client.GetPublicKey(keyVersionName);
    
            // Return the ciphertext.
            return result;
        }
    }

    Go

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

    import (
    	"context"
    	"crypto/x509"
    	"encoding/pem"
    	"fmt"
    	"hash/crc32"
    	"io"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    )
    
    // getPublicKey retrieves the public key from an asymmetric key pair on
    // Cloud KMS.
    func getPublicKey(w io.Writer, name string) error {
    	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"
    
    	// 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.GetPublicKeyRequest{
    		Name: name,
    	}
    
    	// Call the API.
    	result, err := client.GetPublicKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get public key: %w", err)
    	}
    
    	// The 'Pem' field is the raw string representation of the public key.
    	// Convert 'Pem' into bytes for further processing.
    	key := []byte(result.Pem)
    
    	// Optional, but recommended: perform integrity verification on result.
    	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    	// https://cloud.google.com/kms/docs/data-integrity-guidelines
    	crc32c := func(data []byte) uint32 {
    		t := crc32.MakeTable(crc32.Castagnoli)
    		return crc32.Checksum(data, t)
    	}
    	if int64(crc32c(key)) != result.PemCrc32C.Value {
    		return fmt.Errorf("getPublicKey: response corrupted in-transit")
    	}
    
    	// Optional - parse the public key. This transforms the string key into a Go
    	// PublicKey.
    	block, _ := pem.Decode(key)
    	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
    	if err != nil {
    		return fmt.Errorf("failed to parse public key: %w", err)
    	}
    	fmt.Fprintf(w, "Retrieved public key: %v\n", publicKey)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKeyVersionName;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.PublicKey;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    
    public class GetPublicKey {
    
      public void getPublicKey() throws IOException, GeneralSecurityException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String keyId = "my-key";
        String keyVersionId = "123";
        getPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
      }
    
      // Get the public key associated with an asymmetric key.
      public void getPublicKey(
          String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
          throws IOException, GeneralSecurityException {
        // 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 key version name from the project, location, key ring, key,
          // and key version.
          CryptoKeyVersionName keyVersionName =
              CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);
    
          // Get the public key.
          PublicKey publicKey = client.getPublicKey(keyVersionName);
          System.out.printf("Public key: %s%n", publicKey.getPem());
        }
      }
    }

    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 keyRingId = 'my-key-ring';
    // const keyId = 'my-key';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the key version name
    const versionName = client.cryptoKeyVersionPath(
      projectId,
      locationId,
      keyRingId,
      keyId,
      versionId
    );
    
    async function getPublicKey() {
      const [publicKey] = await client.getPublicKey({
        name: versionName,
      });
    
      // Optional, but recommended: perform integrity verification on publicKey.
      // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
      // https://cloud.google.com/kms/docs/data-integrity-guidelines
      const crc32c = require('fast-crc32c');
      if (publicKey.name !== versionName) {
        throw new Error('GetPublicKey: request corrupted in-transit');
      }
      if (crc32c.calculate(publicKey.pem) !== Number(publicKey.pemCrc32c.value)) {
        throw new Error('GetPublicKey: response corrupted in-transit');
      }
    
      console.log(`Public key pem: ${publicKey.pem}`);
    
      return publicKey;
    }
    
    return getPublicKey();

    PHP

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

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\GetPublicKeyRequest;
    
    function get_public_key(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $keyId = 'my-key',
        string $versionId = '123'
    ) {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the key version name.
        $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId);
    
        // Call the API.
        $getPublicKeyRequest = (new GetPublicKeyRequest())
            ->setName($keyVersionName);
        $publicKey = $client->getPublicKey($getPublicKeyRequest);
        printf('Public key: %s' . PHP_EOL, $publicKey->getPem());
    
        return $publicKey;
    }

    Python

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

    from google.cloud import kms
    
    
    def get_public_key(
        project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
    ) -> kms.PublicKey:
        """
        Get the public key for an asymmetric key.
    
        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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to use (e.g. 'my-key').
            version_id (string): ID of the key to use (e.g. '1').
    
        Returns:
            PublicKey: Cloud KMS public key response.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the key version name.
        key_version_name = client.crypto_key_version_path(
            project_id, location_id, key_ring_id, key_id, version_id
        )
    
        # Call the API.
        public_key = client.get_public_key(request={"name": key_version_name})
    
        # Optional, but recommended: perform integrity verification on public_key.
        # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
        # https://cloud.google.com/kms/docs/data-integrity-guidelines
        if not public_key.name == key_version_name:
            raise Exception("The request sent to the server was corrupted in-transit.")
        # See crc32c() function defined below.
        if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
            raise Exception(
                "The response received from the server was corrupted in-transit."
            )
        # End integrity verification
    
        print(f"Public key: {public_key.pem}")
        return public_key
    
    
    def crc32c(data: bytes) -> int:
        """
        Calculates the CRC32C checksum of the provided data.
        Args:
            data: the bytes over which the checksum should be calculated.
        Returns:
            An int representing the CRC32C checksum of the provided bytes.
        """
        import crcmod  # type: ignore
    
        crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
        return crc32c_fun(data)
    
    

    Ruby

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

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # key_ring_id = "my-key-ring"
    # key_id      = "my-key"
    # version_id  = "123"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the key version name.
    key_version_name = client.crypto_key_version_path project:            project_id,
                                                      location:           location_id,
                                                      key_ring:           key_ring_id,
                                                      crypto_key:         key_id,
                                                      crypto_key_version: version_id
    
    # Call the API.
    public_key = client.get_public_key name: key_version_name
    puts "Public key: #{public_key.pem}"

    API

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

    呼叫 CryptoKeyVersions.getPublicKey 方法,擷取公開金鑰。

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION/publicKey?public_key_format=PUBLIC_KEY_FORMAT" \
        --request "GET" \
        --header "authorization: Bearer TOKEN"
    

    更改下列內容:

    • PROJECT_ID:包含金鑰環的專案 ID。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • KEY_NAME:金鑰名稱。
    • KEY_VERSION:金鑰版本號碼。
    • PUBLIC_KEY_FORMAT:您要匯出公開金鑰的格式。如要使用 PQC 演算法 (預覽版),請使用 NIST_PQC。對於所有其他鍵,您可以使用 PEM 或省略這個參數。

    如果省略非 PQC 金鑰的公開金鑰格式,輸出內容會類似下列內容:

    {
      "pem": "-----BEGIN PUBLIC KEY-----\nQ29uZ3JhdHVsYXRpb25zLCB5b3UndmUgZGlzY292ZX
              JlZCB0aGF0IHRoaXMgaXNuJ3QgYWN0dWFsbHkgYSBwdWJsaWMga2V5ISBIYXZlIGEgbmlj
              ZSBkYXkgOik=\n-----END PUBLIC KEY-----\n",
      "algorithm": "ALGORITHM",
      "pemCrc32c": "2561089887",
      "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
               KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
               KEY_VERSION",
      "protectionLevel": "PROTECTION_LEVEL"
    }

    如果是公開金鑰格式為 NIST_PQC 的 PQC 演算法,輸出內容會類似以下範例:

    {
      "publicKeyFormat": "NIST_PQC",
      "publicKey": {
        "crc32cChecksum": "1985843562",
        "data": "kdcOIrFCC5kN8S4i0+R+AoSc9gYIJ9jEQ6zG235ZmCQ="
      }
      "algorithm": "ALGORITHM",
      "name": "projects/PROJECT_ID/locations/LOCATION/keyRings/
               KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/
               KEY_VERSION",
      "protectionLevel": "PROTECTION_LEVEL"
    }

    將公開金鑰轉換為 JWK 格式

    Cloud KMS 可讓您以 PEM 格式擷取公開金鑰。 部分應用程式可能需要其他金鑰格式,例如 JSON Web Key (JWK)。如要進一步瞭解 JWK 格式,請參閱 RFC 7517

    如要將公開金鑰轉換為 JWK 格式,請按照下列步驟操作:

    Go

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

    import (
    	"context"
    	"crypto/x509"
    	"encoding/json"
    	"encoding/pem"
    	"fmt"
    	"hash/crc32"
    	"io"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    	"github.com/lestrrat-go/jwx/v2/jwk"
    )
    
    // getPublicKeyJwk retrieves the public key from an asymmetric key pair on Cloud KMS.
    func getPublicKeyJwk(w io.Writer, cryptoKeyVersionName string) error {
    	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"
    
    	// 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.GetPublicKeyRequest{
    		Name: cryptoKeyVersionName,
    	}
    
    	// Call the API to get the public key.
    	result, err := client.GetPublicKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get public key: %w", err)
    	}
    
    	// The 'Pem' field is the raw string representation of the public key.
    	// Convert 'Pem' into bytes for further processing.
    	key := []byte(result.Pem)
    
    	// Optional, but recommended: perform integrity verification on result.
    	// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
    	// https://cloud.google.com/kms/docs/data-integrity-guidelines
    	crc32c := func(data []byte) uint32 {
    		t := crc32.MakeTable(crc32.Castagnoli)
    		return crc32.Checksum(data, t)
    	}
    	if int64(crc32c(key)) != result.PemCrc32C.Value {
    		return fmt.Errorf("getPublicKey: response corrupted in-transit")
    	}
    
    	// Optional - parse the public key.
    	// This transforms the string key into a Go PublicKey.
    	block, _ := pem.Decode(key)
    	_, err = x509.ParsePKIXPublicKey(block.Bytes)
    	if err != nil {
    		return fmt.Errorf("failed to parse public key: %w", err)
    	}
    
    	// If all above checks pass, convert it into JWK format.
    	jwkKey, err := jwk.ParseKey(key, jwk.WithPEM(true))
    	if err != nil {
    		return fmt.Errorf("Failed to parse the PEM public key: %w", err)
    	}
    
    	fmt.Fprintf(w, "The public key in JWK format: ")
    	json.NewEncoder(w).Encode(jwkKey)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKeyVersionName;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.PublicKey;
    // NOTE: The library nimbusds is NOT endorsed for anything beyond conversion to JWK.
    import com.nimbusds.jose.JOSEException;
    import com.nimbusds.jose.jwk.JWK;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    
    public class ConvertPublicKeyToJwk {
    
      public void convertPublicKey() throws IOException, GeneralSecurityException, JOSEException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String keyId = "my-key";
        String keyVersionId = "123";
        convertPublicKey(projectId, locationId, keyRingId, keyId, keyVersionId);
      }
    
      // (Get and) Convert the public key associated with an asymmetric key.
      public void convertPublicKey(
          String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
          throws IOException, GeneralSecurityException, JOSEException {
        // 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 key version name from the project, location, key ring, key,
          // and key version.
          CryptoKeyVersionName keyVersionName =
              CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);
    
          // Get the public key and convert it to JWK format.
          PublicKey publicKey = client.getPublicKey(keyVersionName);
          JWK jwk = JWK.parseFromPEMEncodedObjects(publicKey.getPem());
          System.out.println(jwk.toJSONString());
        }
      }
    }

    Python

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

    from google.cloud import kms
    from jwcrypto import jwk
    
    
    def get_public_key_jwk(
        project_id: str, location_id: str, key_ring_id: str, key_id: str, version_id: str
    ) -> kms.PublicKey:
        """
        Get the public key of an asymmetric key in JWK format.
    
        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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to use (e.g. 'my-key').
            version_id (string): ID of the key to use (e.g. '1').
    
        Returns:
            PublicKey: Cloud KMS public key response.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the key version name.
        key_version_name = client.crypto_key_version_path(
            project_id, location_id, key_ring_id, key_id, version_id
        )
    
        # Call the API.
        public_key = client.get_public_key(request={"name": key_version_name})
    
        # Optional, but recommended: perform integrity verification on public_key.
        # For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
        # https://cloud.google.com/kms/docs/data-integrity-guidelines
        if not public_key.name == key_version_name:
            raise Exception("The request sent to the server was corrupted in-transit.")
        # See crc32c() function defined below.
        if not public_key.pem_crc32c == crc32c(public_key.pem.encode("utf-8")):
            raise Exception(
                "The response received from the server was corrupted in-transit."
            )
        # End integrity verification
    
        # Convert to JWK format.
        jwk_key = jwk.JWK.from_pem(public_key.pem.encode())
        return jwk_key.export(private_key=False)
    
    
    def crc32c(data: bytes) -> int:
        """
        Calculates the CRC32C checksum of the provided data.
        Args:
            data: the bytes over which the checksum should be calculated.
        Returns:
            An int representing the CRC32C checksum of the provided bytes.
        """
        import crcmod  # type: ignore
    
        crc32c_fun = crcmod.predefined.mkPredefinedCrcFun("crc-32c")
        return crc32c_fun(data)
    
    

    控管非對稱金鑰的存取權

    針對非對稱式金鑰,簽署者或驗證者必須具備適當的權限或角色。

    • 如果使用者或服務將執行簽署,請授予非對稱金鑰的 cloudkms.cryptoKeyVersions.useToSign 權限。

    • 如果使用者或服務將擷取公開金鑰,請授予非對稱金鑰的 cloudkms.cryptoKeyVersions.viewPublicKey。驗證簽名時須使用公開金鑰。

    請參閱權限與角色一文,進一步瞭解 Cloud KMS 版本的權限和角色。

    建立 MAC 簽署金鑰

    控制台

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

      前往「金鑰管理」

    2. 找出您要在哪個金鑰環中建立金鑰,然後按一下該金鑰環名稱。

    3. 按一下 [Create key] (建立金鑰)

    4. 在「金鑰名稱」中,輸入金鑰的名稱。

    5. 在「Protection level」(防護等級) 中,選取「Software」(軟體) 或「HSM」

    6. 在「Key material」(金鑰內容) 中,選取「Generated key」(產生的金鑰)

    7. 針對「Purpose」(目的),選取「MAC signing/verification」

    8. 選用:在「演算法」部分,選取 HMAC 簽署演算法

    9. 點選「建立」

    gcloud

    如要在指令列上使用 Cloud KMS,請先安裝或升級至最新版 Google Cloud CLI

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "mac" \
        --default-algorithm "ALGORITHM" \
        --protection-level "PROTECTION_LEVEL"
    

    更改下列內容:

    • KEY_NAME:金鑰名稱。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • ALGORITHM:HMAC 簽署演算法,例如 hmac-sha256。如要查看所有支援的 HMAC 演算法,請參閱 HMAC 簽署演算法
    • PROTECTION_LEVEL:金鑰的防護等級,例如 hsm。您可以省略 software金鑰的 --protection-level 標記。

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

    C#

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

    
    using Google.Cloud.Kms.V1;
    using Google.Protobuf.WellKnownTypes;
    
    public class CreateKeyMacSample
    {
        public CryptoKey CreateKeyMac(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-mac-key")
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
    
            // Build the parent key ring name.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
    
            // Build the key.
            CryptoKey key = new CryptoKey
            {
                Purpose = CryptoKey.Types.CryptoKeyPurpose.Mac,
                VersionTemplate = new CryptoKeyVersionTemplate
                {
                    Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.HmacSha256,
                },
    
                // Optional: customize how long key versions should be kept before destroying.
                DestroyScheduledDuration = new Duration
                {
                    Seconds = 24 * 60 * 60,
                }
            };
    
            // Call the API.
            CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
    
            // Return the result.
            return result;
        }
    }

    Go

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

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    	"google.golang.org/protobuf/types/known/durationpb"
    )
    
    // createKeyMac creates a new key for use with MacSign.
    func createKeyMac(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-mac-key"
    
    	// 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.CreateCryptoKeyRequest{
    		Parent:      parent,
    		CryptoKeyId: id,
    		CryptoKey: &kmspb.CryptoKey{
    			Purpose: kmspb.CryptoKey_MAC,
    			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
    				Algorithm: kmspb.CryptoKeyVersion_HMAC_SHA256,
    			},
    
    			// Optional: customize how long key versions should be kept before destroying.
    			DestroyScheduledDuration: durationpb.New(24 * time.Hour),
    		},
    	}
    
    	// Call the API.
    	result, err := client.CreateCryptoKey(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create key: %w", err)
    	}
    	fmt.Fprintf(w, "Created key: %s\n", result.Name)
    	return nil
    }
    

    Java

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

    import com.google.cloud.kms.v1.CryptoKey;
    import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
    import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
    import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
    import com.google.cloud.kms.v1.KeyManagementServiceClient;
    import com.google.cloud.kms.v1.KeyRingName;
    import java.io.IOException;
    
    public class CreateKeyMac {
    
      public void createKeyMac() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "us-east1";
        String keyRingId = "my-key-ring";
        String id = "my-mac-key";
        createKeyMac(projectId, locationId, keyRingId, id);
      }
    
      // Create a new key for use with MacSign.
      public void createKeyMac(String projectId, String locationId, String keyRingId, 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, location, and key ring.
          KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
    
          // Build the mac key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.MAC)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.HMAC_SHA256))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created mac key %s%n", createdKey.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 keyRingId = 'my-key-ring';
    // const id = 'my-mac-key';
    
    // Imports the Cloud KMS library
    const {KeyManagementServiceClient} = require('@google-cloud/kms');
    
    // Instantiates a client
    const client = new KeyManagementServiceClient();
    
    // Build the parent key ring name
    const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
    
    async function createKeyMac() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'MAC',
          versionTemplate: {
            algorithm: 'HMAC_SHA256',
          },
    
          // Optional: customize how long key versions should be kept before
          // destroying.
          destroyScheduledDuration: {seconds: 60 * 60 * 24},
        },
      });
    
      console.log(`Created mac key: ${key.name}`);
      return key;
    }
    
    return createKeyMac();

    PHP

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

    use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
    use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
    use Google\Cloud\Kms\V1\CryptoKey;
    use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
    use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
    use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
    use Google\Protobuf\Duration;
    
    function create_key_mac(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-mac-key'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::MAC)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::HMAC_SHA256)
            )
    
            // Optional: customize how long key versions should be kept before destroying.
            ->setDestroyScheduledDuration((new Duration())
                ->setSeconds(24 * 60 * 60)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created mac key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

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

    
    import datetime
    
    from google.cloud import kms
    from google.protobuf import duration_pb2  # type: ignore
    
    
    def create_key_mac(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new key in Cloud KMS for HMAC operations.
    
        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 Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to create (e.g. 'my-mac-key').
    
        Returns:
            CryptoKey: Cloud KMS key.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent key ring name.
        key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    
        # Build the key.
        purpose = kms.CryptoKey.CryptoKeyPurpose.MAC
        algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.HMAC_SHA256
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
            # Optional: customize how long key versions should be kept before
            # destroying.
            "destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
                datetime.timedelta(days=1)
            ),
        }
    
        # Call the API.
        created_key = client.create_crypto_key(
            request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
        )
        print(f"Created mac key: {created_key.name}")
        return created_key
    
    

    Ruby

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

    # TODO(developer): uncomment these values before running the sample.
    # project_id  = "my-project"
    # location_id = "us-east1"
    # key_ring_id = "my-key-ring"
    # id          = "my-mac-key"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent key ring name.
    key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
    
    # Build the key.
    key = {
      purpose:          :MAC,
      version_template: {
        algorithm: :HMAC_SHA256
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created mac key: #{created_key.name}"

    API

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

    如要建立金鑰,請使用 CryptoKey.create 方法:

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --data '{"purpose": "MAC", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'
    

    更改下列內容:

    • PROJECT_ID:包含金鑰環的專案 ID。
    • LOCATION:金鑰環的 Cloud KMS 位置。
    • KEY_RING:金鑰所屬金鑰環的名稱。
    • KEY_NAME:金鑰名稱。
    • PROTECTION_LEVEL:金鑰的防護等級,例如 SOFTWAREHSM
    • ALGORITHM:HMAC 簽署演算法,例如 HMAC_SHA256。 如要查看所有支援的 HMAC 演算法,請參閱 HMAC 簽署演算法

    後續步驟