Mengimpor versi kunci ke Cloud KMS

Topik ini menunjukkan cara mengimpor kunci kriptografis ke Cloud HSM atau Cloud Key Management Service sebagai versi kunci baru.

Untuk detail selengkapnya tentang cara mengimpor kunci, termasuk batasan dan pembatasan, lihat impor kunci.

Anda dapat menyelesaikan langkah-langkah dalam topik ini dalam waktu 5 hingga 10 menit, tidak termasuk langkah Sebelum memulai. Menggabungkan kunci secara manual akan menambah kerumitan pada tugas.

Sebelum memulai

Sebaiknya buat project baru untuk menguji fitur ini, untuk memudahkan pembersihan setelah pengujian, dan untuk memastikan bahwa Anda memiliki izin Identity and Access Management (IAM) yang memadai untuk mengimpor kunci.

Sebelum dapat mengimpor kunci, Anda harus menyiapkan project, sistem lokal, dan kunci itu sendiri.

Mempersiapkan proyek

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  3. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  4. Enable the required API.

    Enable the API

  5. Menginstal Google Cloud CLI.
  6. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  7. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  8. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  9. Enable the required API.

    Enable the API

  10. Menginstal Google Cloud CLI.
  11. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  12. Pengguna yang melakukan impor memerlukan izin IAM berikut untuk membuat key ring, kunci, dan tugas impor. Jika pengguna bukan pemilik project, Anda dapat menetapkan kedua dari dua peran yang telah ditetapkan berikut kepada pengguna:

    • roles/editor
    • roles/cloudkms.importer

    Untuk mengetahui informasi selengkapnya tentang peran IAM yang tersedia dan izin untuk Cloud KMS, lihat Izin dan peran.

Menyiapkan sistem lokal

Siapkan sistem lokal dengan memilih salah satu opsi berikut. Penggabungan kunci otomatis direkomendasikan untuk sebagian besar pengguna.

Menyiapkan kunci

Pastikan algoritma dan panjang kunci Anda didukung. Algoritma yang diizinkan untuk kunci bergantung pada apakah kunci tersebut digunakan untuk enkripsi simetris, enkripsi asimetris, atau penandatanganan asimetris, serta apakah kunci disimpan dalam software atau HSM. Anda menentukan algoritma kunci sebagai bagian dari permintaan impor.

Secara terpisah, Anda juga harus memverifikasi cara kunci dienkode, dan melakukan penyesuaian jika perlu.

Hal berikut tidak dapat diubah untuk versi kunci setelah dibuat atau diimpor:

  • Tingkat perlindungan menunjukkan apakah kunci tetap ada dalam software, di HSM, atau dalam sistem pengelolaan kunci eksternal. Materi kunci tidak dapat dipindahkan dari salah satu lingkungan penyimpanan ini ke lingkungan penyimpanan lainnya. Semua versi kunci memiliki level perlindungan yang sama.

  • Tujuan menunjukkan apakah versi kunci digunakan untuk enkripsi simetris, enkripsi asimetris, atau penandatanganan asimetris. Tujuan kunci ini membatasi kemungkinan algoritma yang dapat digunakan untuk membuat versi kunci tersebut. Semua versi kunci memiliki fungsi yang sama.

Jika tidak memiliki kunci untuk diimpor, tetapi ingin memvalidasi prosedur impor kunci, Anda dapat membuat kunci simetris di sistem lokal, menggunakan perintah berikut:

openssl rand 32 > ${HOME}/test.bin

Gunakan kunci ini hanya untuk pengujian. Kunci yang dibuat dengan cara ini mungkin tidak sesuai untuk penggunaan produksi.

Jika Anda perlu menggabungkan kunci secara manual, lakukan hal tersebut sebelum melanjutkan prosedur dalam topik ini.

Membuat kunci dan key ring target

Kunci Cloud KMS adalah objek container yang berisi nol atau beberapa versi kunci. Setiap versi kunci berisi kunci kriptografis.

Saat Anda mengimpor kunci ke Cloud KMS atau Cloud HSM, kunci yang diimpor akan menjadi versi kunci baru pada kunci Cloud KMS atau Cloud HSM yang sudah ada. Pada bagian selanjutnya dari topik ini, kunci ini disebut kunci target. Kunci target harus ada sebelum Anda dapat mengimpor materi kunci ke dalamnya.

Mengimpor versi kunci tidak akan memengaruhi versi kunci yang sudah ada. Namun, sebaiknya buat kunci kosong saat menguji impor kunci. Kunci kosong tidak memiliki versi, tidak aktif, dan tidak dapat digunakan.

Secara opsional, Anda dapat menentukan bahwa kunci yang baru dibuat hanya dapat berisi versi yang diimpor, sehingga mencegah pembuatan versi baru secara tidak sengaja di Cloud KMS.

Sebuah kunci ada pada key ring; dalam topik ini, key ring ini disebut key ring target. Lokasi key ring target menentukan lokasi tempat materi kunci tersedia setelah impor. Kunci Cloud HSM tidak dapat dibuat atau diimpor di beberapa lokasi. Setelah dibuat, kunci tidak dapat dipindahkan ke key ring atau lokasi lain.

Ikuti langkah-langkah berikut untuk membuat kunci kosong pada key ring baru menggunakan Google Cloud CLI atau Konsol Google Cloud.

Konsol

  1. Di konsol Google Cloud, buka halaman Key Management.

    Buka Key Management

  2. Klik Create key ring.

  3. Di kolom Key ring name, masukkan nama untuk key ring.

  4. Di bagian Jenis lokasi, pilih jenis lokasi dan lokasi.

  5. Klik Create. Halaman Buat kunci akan terbuka.

  6. Di kolom Key name, masukkan nama untuk kunci Anda.

  7. Untuk Tingkat perlindungan, pilih Software atau HSM, lalu klik Continue.

  8. Untuk Key material, pilih Imported key, lalu klik Continue. Tindakan ini akan mencegah pembuatan versi kunci awal.

  9. Tetapkan Destination dan Algorithm untuk kunci, lalu klik Continue.

  10. Opsional: Jika Anda ingin kunci ini hanya berisi versi kunci yang diimpor, pilih Restrict key version to import only. Hal ini dapat mencegah Anda membuat versi kunci baru di Cloud KMS secara tidak sengaja.

  11. Opsional: Untuk kunci yang diimpor, rotasi otomatis dinonaktifkan secara default. Untuk mengaktifkan rotasi otomatis, pilih nilai dari kolom KeyRotation periode.

    Jika Anda mengaktifkan rotasi otomatis, versi kunci baru akan dibuat di Cloud KMS, dan versi kunci yang diimpor tidak akan lagi menjadi versi kunci default setelah rotasi.

  12. Klik Create.

gcloud

Untuk menggunakan Cloud KMS di command line, Instal atau upgrade Google Cloud CLI ke versi terbaru terlebih dahulu.

  1. Buat key ring target. Jika Anda ingin mengimpor ke kunci Cloud HSM, pilih lokasi yang memiliki dukungan untuk Cloud HSM.

    gcloud kms keyrings create KEY_RING \
      --location LOCATION
    

    Anda dapat mempelajari membuat key ring lebih lanjut.

  2. Buat kunci target.

    • Tentukan tujuan kunci.
    • Cegah pembuatan versi awal menggunakan tanda --skip-initial-version-creation.
    • Opsional: Cegah pembuatan versi baru di Cloud KMS menggunakan flag --import-only.
    • Opsional: Jangan tentukan kebijakan rotasi. Jika Anda mengaktifkan rotasi otomatis, versi kunci baru akan dibuat di Cloud KMS, dan versi kunci yang diimpor tidak akan lagi menjadi versi kunci default setelah rotasi. Anda mungkin tidak menentukan kebijakan rotasi jika menentukan flag --import-only.
    gcloud kms keys create KEY_NAME \
      --location LOCATION \
      --keyring KEY_RING \
      --purpose PURPOSE \
      --skip-initial-version-creation \
      --import-only
    

    Anda dapat mempelajari lebih lanjut cara membuat kunci Cloud KMS atau kunci Cloud HSM.

Go

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu lalu instal Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// createKeyForImport creates a new asymmetric signing key in Cloud HSM.
func createKeyForImport(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-imported-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{
				ProtectionLevel: kmspb.ProtectionLevel_HSM,
				Algorithm:       kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256,
			},
			// Ensure that only imported versions may be added to this key.
			ImportOnly: true,
		},
		SkipInitialVersionCreation: true,
	}

	// 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

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Java SDK Cloud KMS.

import com.google.cloud.kms.v1.CreateCryptoKeyRequest;
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.cloud.kms.v1.ProtectionLevel;
import java.io.IOException;

public class CreateKeyForImport {

  public void createKeyForImport() 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-import-key";
    createKeyForImport(projectId, locationId, keyRingId, id);
  }

  // Create a new crypto key to hold imported key versions.
  public void createKeyForImport(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);

      // Create the crypto key.
      CryptoKey createdKey =
          client.createCryptoKey(
              CreateCryptoKeyRequest.newBuilder()
                  .setParent(keyRingName.toString())
                  .setCryptoKeyId(id)
                  .setCryptoKey(
                      CryptoKey.newBuilder()
                          .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
                          .setVersionTemplate(
                              CryptoKeyVersionTemplate.newBuilder()
                                  .setProtectionLevel(ProtectionLevel.HSM)
                                  .setAlgorithm(CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256))
                          // Ensure that only imported versions may be
                          // added to this key.
                          .setImportOnly(true))
                  .setSkipInitialVersionCreation(true)
                  .build());

      System.out.printf("Created crypto key %s%n", createdKey.getName());
    }
  }
}

Node.js

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu, lalu instal Node.js SDK Cloud KMS.

//
// 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-imported-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 createKeyForImport() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
        protectionLevel: 'HSM',
      },
      // Optional: ensure that only imported versions may be added to this
      // key.
      importOnly: true,
    },
    // Do not allow KMS to generate an initial version of this key.
    skipInitialVersionCreation: true,
  });

  console.log(`Created key for import: ${key.name}`);
  return key;
}

return createKeyForImport();

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu lalu instal Cloud KMS Python SDK.

from google.cloud import kms

def create_key_for_import(
    project_id: str, location_id: str, key_ring_id: str, crypto_key_id: str
) -> None:
    """

    Sets up an empty CryptoKey within a KeyRing for import.

    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').
        crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key. For more information regarding allowed values of these fields, see:
    # https://googleapis.dev/python/cloudkms/latest/_modules/google/cloud/kms_v1/types/resources.html
    purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN
    algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256
    protection_level = kms.ProtectionLevel.HSM
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
            "protection_level": protection_level,
        },
    }

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Call the API.
    created_key = client.create_crypto_key(
        request={
            "parent": key_ring_name,
            "crypto_key_id": crypto_key_id,
            "crypto_key": key,
        }
    )
    print(f"Created hsm key: {created_key.name}")

API

Contoh ini menggunakan curl sebagai klien HTTP untuk menunjukkan penggunaan API. Untuk informasi selengkapnya tentang kontrol akses, lihat Mengakses Cloud KMS API.

  1. Membuat key ring baru:

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings?keyRingId=KEY_RING" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --header "x-goog-user-project: PROJECT_ID" \
        --data "{}"
    

    Lihat dokumentasi API KeyRing.create untuk informasi selengkapnya.

  2. Buat kunci khusus impor yang kosong:

    curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?cryptoKeyId=KEY_NAME&skipInitialVersionCreation=true&importOnly=true" \
        --request "POST" \
        --header "authorization: Bearer TOKEN" \
        --header "content-type: application/json" \
        --header "x-goog-user-project: PROJECT_ID" \
        --data "{"purpose":"PURPOSE", "versionTemplate":{"protectionLevel":"PROTECTION_LEVEL","algorithm":"ALGORITHM"}}"
    

    Lihat dokumentasi API CryptoKey.create untuk informasi selengkapnya.

Key ring dan key sudah ada, tetapi kunci tersebut tidak berisi materi kunci, tidak memiliki versi, dan tidak aktif. Selanjutnya, Anda membuat tugas impor.

Membuat tugas impor

Tugas impor menentukan karakteristik kunci yang diimpornya, termasuk properti yang tidak dapat diubah setelah kunci diimpor.

Tingkat perlindungan menentukan apakah kunci yang diimpor oleh tugas impor ini akan berada dalam software, di HSM, atau dalam sistem pengelolaan kunci eksternal. Tingkat perlindungan tidak dapat diubah setelah kunci pada akhirnya diimpor.

Metode impor menentukan algoritma yang digunakan untuk membuat kunci penggabungan yang melindungi kunci yang diimpor selama pengiriman dari sistem lokal Anda ke project Google Cloud target. Anda dapat memilih kunci RSA 3072-bit atau 4096-bit. Sebaiknya gunakan kunci penggabungan 3072-bit, kecuali jika Anda memiliki persyaratan khusus.

Anda dapat membuat tugas impor menggunakan gcloud CLI, Google Cloud Console, atau Cloud Key Management Service API.

Konsol

  1. Buka halaman Key Management di konsol Google Cloud.

    Buka halaman Key Management

  2. Klik nama key ring target.

  3. Setel Tingkat perlindungan ke Software atau HSM. Gunakan tingkat perlindungan yang sama seperti yang Anda tetapkan untuk kunci target.

  4. Klik Buat tugas impor.

  5. Di kolom Name, masukkan nama untuk tugas impor Anda.

  6. Dari dropdown Import method, tetapkan metode impor ke RSA 3072 bit atau RSA 4096 bit.

  7. Klik Create.

gcloud

Untuk menggunakan Cloud KMS di command line, Instal atau upgrade Google Cloud CLI ke versi terbaru terlebih dahulu.

Gunakan perintah seperti berikut untuk membuat tugas impor.

gcloud kms import-jobs create IMPORT_JOB \
  --location LOCATION \
  --keyring KEY_RING \
  --import-method IMPORT_METHOD \
  --protection-level PROTECTION_LEVEL
  • Gunakan key ring dan lokasi yang sama dengan kunci target.
  • Setel tingkat perlindungan ke software atau hsm.
  • Tetapkan metode impor ke rsa-oaep-3072-sha1-aes-256 rsa-oaep-4096-sha1-aes-256, rsa-oaep-3072-sha256-aes-256, rsa-oaep-4096-sha256-aes-256, rsa-oaep-3072-sha256, atau rsa-oaep-4096-sha256.

Go

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu lalu instal Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// createImportJob creates a new job for importing keys into KMS.
func createImportJob(w io.Writer, parent, id string) error {
	// parent := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring"
	// id := "my-import-job"

	// 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.CreateImportJobRequest{
		Parent:      parent,
		ImportJobId: id,
		ImportJob: &kmspb.ImportJob{
			// See allowed values and their descriptions at
			// https://cloud.google.com/kms/docs/algorithms#protection_levels
			ProtectionLevel: kmspb.ProtectionLevel_HSM,
			// See allowed values and their descriptions at
			// https://cloud.google.com/kms/docs/key-wrapping#import_methods
			ImportMethod: kmspb.ImportJob_RSA_OAEP_3072_SHA1_AES_256,
		},
	}

	// Call the API.
	result, err := client.CreateImportJob(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create import job: %w", err)
	}
	fmt.Fprintf(w, "Created import job: %s\n", result.Name)
	return nil
}

Java

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Java SDK Cloud KMS.

import com.google.cloud.kms.v1.ImportJob;
import com.google.cloud.kms.v1.ImportJob.ImportMethod;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.cloud.kms.v1.ProtectionLevel;
import java.io.IOException;

public class CreateImportJob {

  public void createImportJob() 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-import-job";
    createImportJob(projectId, locationId, keyRingId, id);
  }

  // Create a new import job.
  public void createImportJob(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 import job to create, with parameters.
      ImportJob importJob =
          ImportJob.newBuilder()
              // See allowed values and their descriptions at
              // https://cloud.google.com/kms/docs/algorithms#protection_levels
              .setProtectionLevel(ProtectionLevel.HSM)
              // See allowed values and their descriptions at
              // https://cloud.google.com/kms/docs/key-wrapping#import_methods
              .setImportMethod(ImportMethod.RSA_OAEP_3072_SHA1_AES_256)
              .build();

      // Create the import job.
      ImportJob createdImportJob = client.createImportJob(keyRingName, id, importJob);
      System.out.printf("Created import job %s%n", createdImportJob.getName());
    }
  }
}

Node.js

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu, lalu instal Node.js SDK Cloud KMS.

//
// 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-import-job';

// 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 createImportJob() {
  const [importJob] = await client.createImportJob({
    parent: keyRingName,
    importJobId: id,
    importJob: {
      protectionLevel: 'HSM',
      importMethod: 'RSA_OAEP_3072_SHA256',
    },
  });

  console.log(`Created import job: ${importJob.name}`);
  return importJob;
}

return createImportJob();

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu lalu instal Cloud KMS Python SDK.

from google.cloud import kms

def create_import_job(
    project_id: str, location_id: str, key_ring_id: str, import_job_id: str
) -> None:
    """
    Create a new import job 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').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified key_ring string.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Set paramaters for the import job, allowed values for ImportMethod and ProtectionLevel found here:
    # https://googleapis.dev/python/cloudkms/latest/_modules/google/cloud/kms_v1/types/resources.html

    import_method = kms.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256
    protection_level = kms.ProtectionLevel.HSM
    import_job_params = {
        "import_method": import_method,
        "protection_level": protection_level,
    }

    # Call the client to create a new import job.
    import_job = client.create_import_job(
        {
            "parent": key_ring_name,
            "import_job_id": import_job_id,
            "import_job": import_job_params,
        }
    )

    print(f"Created import job: {import_job.name}")

API

Contoh ini menggunakan curl sebagai klien HTTP untuk menunjukkan penggunaan API. Untuk informasi selengkapnya tentang kontrol akses, lihat Mengakses Cloud KMS API.

Untuk membuat tugas impor, gunakan metode ImportJobs.create:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/importJobs?import_job_id=IMPORT_JOB_ID" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"import_method": "IMPORT_METHOD", "protection_level": "PROTECTION_LEVEL"}'

Ganti kode berikut:

Memeriksa status tugas impor

Status awal untuk tugas impor adalah PENDING_GENERATION. Jika statusnya adalah ACTIVE, Anda dapat menggunakannya untuk mengimpor kunci.

Tugas impor akan berakhir setelah tiga hari. Jika tugas impor sudah berakhir, Anda harus membuat tugas baru.

Anda dapat memeriksa status tugas impor menggunakan Google Cloud CLI, Konsol Google Cloud, atau Cloud Key Management Service API.

Konsol

  1. Buka halaman Key Management di konsol Google Cloud.

    Buka halaman Key Management

  2. Klik nama key ring yang berisi tugas impor Anda.

  3. Klik tab Impor Tugas di bagian atas halaman.

  4. Status akan terlihat di bagian Status di samping nama tugas impor Anda.

gcloud

Untuk menggunakan Cloud KMS di command line, Instal atau upgrade Google Cloud CLI ke versi terbaru terlebih dahulu.

Saat tugas impor aktif, Anda dapat menggunakannya untuk mengimpor kunci. Proses ini mungkin memerlukan waktu beberapa menit. Gunakan perintah ini untuk memverifikasi bahwa tugas impor aktif. Gunakan lokasi dan keyring tempat Anda membuat tugas impor.

gcloud kms import-jobs describe IMPORT_JOB \
  --location LOCATION \
  --keyring KEY_RING \
  --format="value(state)"

Outputnya mirip dengan hal berikut ini:

state: ACTIVE

Go

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu lalu instal Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// checkStateImportJob checks the state of an ImportJob in KMS.
func checkStateImportJob(w io.Writer, name string) error {
	// name := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/importJobs/my-import-job"

	// 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()

	// Call the API.
	result, err := client.GetImportJob(ctx, &kmspb.GetImportJobRequest{
		Name: name,
	})
	if err != nil {
		return fmt.Errorf("failed to get import job: %w", err)
	}
	fmt.Fprintf(w, "Current state of import job %q: %s\n", result.Name, result.State)
	return nil
}

Java

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Java SDK Cloud KMS.

import com.google.cloud.kms.v1.ImportJob;
import com.google.cloud.kms.v1.ImportJobName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class CheckStateImportJob {

  public void checkStateImportJob() 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 importJobId = "my-import-job";
    checkStateImportJob(projectId, locationId, keyRingId, importJobId);
  }

  // Check the state of an import job in Cloud KMS.
  public void checkStateImportJob(
      String projectId, String locationId, String keyRingId, String importJobId)
      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.
      ImportJobName importJobName = ImportJobName.of(projectId, locationId, keyRingId, importJobId);

      // Retrieve the state of an existing import job.
      ImportJob importJob = client.getImportJob(importJobName);
      System.out.printf(
          "Current state of import job %s: %s%n", importJob.getName(), importJob.getState());
    }
  }
}

Node.js

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu, lalu instal Node.js SDK Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const importJobId = 'my-import-job';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the import job name
const importJobName = client.importJobPath(
  projectId,
  locationId,
  keyRingId,
  importJobId
);

async function checkStateImportJob() {
  const [importJob] = await client.getImportJob({
    name: importJobName,
  });

  console.log(
    `Current state of import job ${importJob.name}: ${importJob.state}`
  );
  return importJob;
}

return checkStateImportJob();

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu lalu instal Cloud KMS Python SDK.

from google.cloud import kms

def check_state_import_job(
    project_id: str, location_id: str, key_ring_id: str, import_job_id: str
) -> None:
    """
    Check the state of an import job 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').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified import_job string.
    import_job_name = client.import_job_path(
        project_id, location_id, key_ring_id, import_job_id
    )

    # Retrieve the state from an existing import job.
    import_job = client.get_import_job(name=import_job_name)

    print(f"Current state of import job {import_job.name}: {import_job.state}")

API

Contoh ini menggunakan curl sebagai klien HTTP untuk menunjukkan penggunaan API. Untuk informasi selengkapnya tentang kontrol akses, lihat Mengakses Cloud KMS API.

Untuk memeriksa status tugas impor, gunakan metode ImportJobs.get:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/importJobs/IMPORT_JOB_ID" \
    --request "GET" \
    --header "authorization: Bearer TOKEN"

Segera setelah tugas impor aktif, Anda dapat membuat permintaan untuk mengimpor kunci.

Mencegah modifikasi tugas impor

Tugas impor menentukan banyak karakteristik kunci yang diimpor, termasuk algoritma kunci dan apakah kunci yang diimpor adalah kunci HSM atau kunci software. Anda dapat mengonfigurasi izin IAM agar pengguna tidak membuat tugas impor, sekaligus mengizinkan mereka menggunakan tugas impor untuk mengimpor kunci.

  1. Berikan izin importjobs.create hanya kepada administrator utama.
  2. Berikan izin importjobs.useToImport untuk tugas impor tertentu kepada operator yang akan menggunakan tugas tersebut untuk mengimpor kunci.
  3. Saat Anda membuat tugas impor, tentukan tingkat perlindungan dan algoritma untuk versi kunci yang diimpor menggunakan tugas tersebut.

Hingga tugas impor berakhir, pengguna yang memiliki importjobs.useToImport dan tidak memiliki izin importjobs.create untuk tugas impor tertentu dapat mengimpor kunci, tetapi tidak dapat mengubah karakteristik tugas impor.

Mengimpor kunci

Setelah memeriksa status tugas impor, Anda dapat membuat permintaan impor.

Anda menggunakan tanda yang berbeda untuk membuat permintaan impor, bergantung pada apakah Anda ingin Google Cloud CLI menggabungkan kunci secara otomatis atau apakah Anda telah menggabungkan kunci secara manual.

Terlepas dari apakah Anda menggabungkan kunci secara manual atau otomatis, Anda harus menetapkan algoritma ke algoritma yang didukung yang cocok dengan panjang kunci sebenarnya yang akan diimpor, dan menentukan tujuan kunci.

  • Kunci dengan tujuan ENCRYPT_DECRYPT menggunakan algoritma google-symmetric-encryption, dan memiliki panjang 32.

  • Kunci dengan ASYMMETRIC_DECRYPT atau ASYMMETRIC_SIGN tujuan mendukung berbagai algoritma dan panjang.

    Tujuan kunci tidak dapat diubah setelah kunci dibuat, tetapi versi kunci berikutnya dapat dibuat dengan panjang yang berbeda dari versi kunci awal.

Menggabungkan dan mengimpor kunci secara otomatis

Jika ingin menggunakan penggabungan otomatis, Anda harus menggunakan Google Cloud CLI. Gunakan perintah seperti berikut. Tetapkan --target-key-file ke lokasi kunci yang belum digabungkan untuk digabungkan dan diimpor. Jangan tetapkan --wrapped-key-file.

Secara opsional, Anda dapat menyetel flag --public-key-file ke lokasi tempat kunci publik telah didownload. Saat mengimpor kunci dalam jumlah besar, hal ini akan mencegah kunci publik didownload pada setiap proses impor. Misalnya, Anda dapat menulis skrip yang mendownload kunci publik satu kali, lalu memberikan lokasinya saat mengimpor setiap kunci.

gcloud kms keys versions import \
    --import-job IMPORT_JOB \
    --location LOCATION \
    --keyring KEY_RING \
    --key KEY_NAME \
    --algorithm ALGORITHM \
    --target-key-file PATH_TO_UNWRAPPED_KEY

Kunci ini digabungkan oleh kunci penggabungan yang terkait dengan tugas impor, dikirim ke Google Cloud, dan diimpor sebagai versi kunci baru pada kunci target.

Mengimpor kunci yang digabungkan secara manual

Gunakan petunjuk di bagian ini untuk mengimpor kunci yang telah Anda gabungkan secara manual. Tetapkan --wrapped-key-file ke lokasi kunci yang Anda gabungkan secara manual. Jangan tetapkan --target-key-file.

Secara opsional, Anda dapat menyetel flag --public-key-file ke lokasi tempat kunci publik telah didownload. Saat mengimpor kunci dalam jumlah besar, hal ini akan mencegah kunci publik didownload pada setiap proses impor. Misalnya, Anda dapat menulis skrip yang mendownload kunci publik satu kali, lalu memberikan lokasinya saat mengimpor setiap kunci.

Konsol

  1. Buka halaman Key Management di Konsol Google Cloud.

  2. Klik nama key ring yang berisi tugas impor Anda. Kunci target ditampilkan bersama dengan tombol lain pada key ring.

  3. Klik nama kunci target, lalu klik Import key version.

  4. Pilih tugas impor dari menu dropdown Pilih tugas impor.

  5. Di pemilih Upload the wrapped key, pilih kunci yang telah Anda gabung.

  6. Jika Anda mengimpor kunci asimetris, pilih algoritma dari menu drop-down Algoritma. Halaman Import key version Anda akan terlihat mirip dengan:

    Impor versi kunci

  7. Klik Import.

gcloud

Untuk menggunakan Cloud KMS di command line, Instal atau upgrade Google Cloud CLI ke versi terbaru terlebih dahulu.

Gunakan perintah seperti berikut.

gcloud kms keys versions import \
  --import-job IMPORT_JOB \
  --location LOCATION \
  --keyring KEY_RING \
  --key KEY_NAME \
  --algorithm ALGORITHM \
  --wrapped-key-file PATH_TO_WRAPPED_KEY

Untuk mengetahui informasi selengkapnya, lihat output perintah gcloud kms keys versions import --help.

Go

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu lalu instal Cloud KMS Go SDK.

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	"github.com/google/tink/go/kwp/subtle"
)

// importManuallyWrappedKey wraps key material and imports it into KMS.
func importManuallyWrappedKey(w io.Writer, importJobName, cryptoKeyName string) error {
	// importJobName := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/importJobs/my-import-job"
	// cryptoKeyName := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/cryptoKeys/my-imported-key"

	// Generate a ECDSA keypair, and format the private key as PKCS #8 DER.
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return fmt.Errorf("failed to generate keypair: %w", err)
	}
	keyBytes, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return fmt.Errorf("failed to format private key: %w", err)
	}

	// 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()

	// Generate a temporary 32-byte key for AES-KWP and wrap the key material.
	kwpKey := make([]byte, 32)
	if _, err := rand.Read(kwpKey); err != nil {
		return fmt.Errorf("failed to generate AES-KWP key: %w", err)
	}
	kwp, err := subtle.NewKWP(kwpKey)
	if err != nil {
		return fmt.Errorf("failed to create KWP cipher: %w", err)
	}
	wrappedTarget, err := kwp.Wrap(keyBytes)
	if err != nil {
		return fmt.Errorf("failed to wrap target key with KWP: %w", err)
	}

	// Retrieve the public key from the import job.
	importJob, err := client.GetImportJob(ctx, &kmspb.GetImportJobRequest{
		Name: importJobName,
	})
	if err != nil {
		return fmt.Errorf("failed to retrieve import job: %w", err)
	}
	pubBlock, _ := pem.Decode([]byte(importJob.PublicKey.Pem))
	pubAny, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
	if err != nil {
		return fmt.Errorf("failed to parse import job public key: %w", err)
	}
	pub, ok := pubAny.(*rsa.PublicKey)
	if !ok {
		return fmt.Errorf("unexpected public key type %T, want *rsa.PublicKey", pubAny)
	}

	// Wrap the KWP key using the import job key.
	wrappedWrappingKey, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, pub, kwpKey, nil)
	if err != nil {
		return fmt.Errorf("failed to wrap KWP key: %w", err)
	}

	// Concatenate the wrapped KWP key and the wrapped target key.
	combined := append(wrappedWrappingKey, wrappedTarget...)

	// Build the request.
	req := &kmspb.ImportCryptoKeyVersionRequest{
		Parent:     cryptoKeyName,
		ImportJob:  importJobName,
		Algorithm:  kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256,
		WrappedKey: combined,
	}

	// Call the API.
	result, err := client.ImportCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to import crypto key version: %w", err)
	}
	fmt.Fprintf(w, "Created crypto key version: %s\n", result.Name)
	return nil
}

Java

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Java SDK Cloud KMS.

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.ImportCryptoKeyVersionRequest;
import com.google.cloud.kms.v1.ImportJob;
import com.google.cloud.kms.v1.ImportJobName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.crypto.tink.subtle.Kwp;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;

public class ImportManuallyWrappedKey {

  public void importManuallyWrappedKey() throws GeneralSecurityException, 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 cryptoKeyId = "my-crypto-key";
    String importJobId = "my-import-job";
    importManuallyWrappedKey(projectId, locationId, keyRingId, cryptoKeyId, importJobId);
  }

  // Generates and imports local key material into Cloud KMS.
  public void importManuallyWrappedKey(
      String projectId, String locationId, String keyRingId, String cryptoKeyId, String importJobId)
      throws GeneralSecurityException, IOException {

    // Generate a new ECDSA keypair, and format the private key as PKCS #8 DER.
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp256r1"));
    KeyPair kp = generator.generateKeyPair();
    byte[] privateBytes = kp.getPrivate().getEncoded();

    // 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 crypto key and import job names from the project, location,
      // key ring, and ID.
      final CryptoKeyName cryptoKeyName =
          CryptoKeyName.of(projectId, locationId, keyRingId, cryptoKeyId);
      final ImportJobName importJobName =
          ImportJobName.of(projectId, locationId, keyRingId, importJobId);

      // Generate a temporary 32-byte key for AES-KWP and wrap the key material.
      byte[] kwpKey = new byte[32];
      new SecureRandom().nextBytes(kwpKey);
      Kwp kwp = new Kwp(kwpKey);
      final byte[] wrappedTargetKey = kwp.wrap(privateBytes);

      // Retrieve the public key from the import job.
      ImportJob importJob = client.getImportJob(importJobName);
      String publicKeyStr = importJob.getPublicKey().getPem();
      // Manually convert PEM to DER. :-(
      publicKeyStr = publicKeyStr.replace("-----BEGIN PUBLIC KEY-----", "");
      publicKeyStr = publicKeyStr.replace("-----END PUBLIC KEY-----", "");
      publicKeyStr = publicKeyStr.replaceAll("\n", "");
      byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
      PublicKey publicKey =
          KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));

      // Wrap the KWP key using the import job key.
      Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
      cipher.init(
          Cipher.ENCRYPT_MODE,
          publicKey,
          new OAEPParameterSpec(
              "SHA-1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
      byte[] wrappedWrappingKey = cipher.doFinal(kwpKey);

      // Concatenate the wrapped KWP key and the wrapped target key.
      ByteString combinedWrappedKeys =
          ByteString.copyFrom(wrappedWrappingKey).concat(ByteString.copyFrom(wrappedTargetKey));

      // Import the wrapped key material.
      CryptoKeyVersion version =
          client.importCryptoKeyVersion(
              ImportCryptoKeyVersionRequest.newBuilder()
                  .setParent(cryptoKeyName.toString())
                  .setImportJob(importJobName.toString())
                  .setAlgorithm(CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256)
                  .setRsaAesWrappedKey(combinedWrappedKeys)
                  .build());

      System.out.printf("Imported: %s%n", version.getName());
    }
  }
}

Node.js

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu, lalu instal Node.js SDK Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const cryptoKeyId = 'my-imported-key';
// const importJobId = 'my-import-job';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the crypto key and importjob resource names
const cryptoKeyName = client.cryptoKeyPath(
  projectId,
  locationId,
  keyRingId,
  cryptoKeyId
);
const importJobName = client.importJobPath(
  projectId,
  locationId,
  keyRingId,
  importJobId
);

async function wrapAndImportKey() {
  // Generate a 32-byte key to import.
  const crypto = require('crypto');
  const targetKey = crypto.randomBytes(32);

  const [importJob] = await client.getImportJob({name: importJobName});

  // Wrap the target key using the import job key
  const wrappedTargetKey = crypto.publicEncrypt(
    {
      key: importJob.publicKey.pem,
      oaepHash: 'sha256',
      padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
    },
    targetKey
  );

  // Import the target key version
  const [version] = await client.importCryptoKeyVersion({
    parent: cryptoKeyName,
    importJob: importJobName,
    algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
    wrappedKey: wrappedTargetKey,
  });

  console.log(`Imported key version: ${version.name}`);
  return version;
}

return wrapAndImportKey();

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu lalu instal Cloud KMS Python SDK.

import os

# Import the client library and Python standard cryptographic libraries.
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import keywrap
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import padding
from google.cloud import kms

def import_manually_wrapped_key(
    project_id: str,
    location_id: str,
    key_ring_id: str,
    crypto_key_id: str,
    import_job_id: str,
) -> None:
    """
    Generates and imports local key material to 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').
        crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Generate some key material in Python and format it in PKCS #8 DER as
    # required by Google Cloud KMS.
    key = ec.generate_private_key(ec.SECP256R1, backends.default_backend())
    formatted_key = key.private_bytes(
        serialization.Encoding.DER,
        serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption(),
    )

    print(f"Generated key bytes: {formatted_key!r}")

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified crypto_key and import_job string.
    crypto_key_name = client.crypto_key_path(
        project_id, location_id, key_ring_id, crypto_key_id
    )
    import_job_name = client.import_job_path(
        project_id, location_id, key_ring_id, import_job_id
    )

    # Generate a temporary 32-byte key for AES-KWP and wrap the key material.
    kwp_key = os.urandom(32)
    wrapped_target_key = keywrap.aes_key_wrap_with_padding(
        kwp_key, formatted_key, backends.default_backend()
    )

    # Retrieve the public key from the import job.
    import_job = client.get_import_job(name=import_job_name)
    import_job_pub = serialization.load_pem_public_key(
        bytes(import_job.public_key.pem, "UTF-8"), backends.default_backend()
    )

    # Wrap the KWP key using the import job key.
    wrapped_kwp_key = import_job_pub.encrypt(
        kwp_key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        ),
    )

    # Import the wrapped key material.
    client.import_crypto_key_version(
        {
            "parent": crypto_key_name,
            "import_job": import_job_name,
            "algorithm": kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256,
            "rsa_aes_wrapped_key": wrapped_kwp_key + wrapped_target_key,
        }
    )

    print(f"Imported: {import_job.name}")

API

Contoh ini menggunakan curl sebagai klien HTTP untuk menunjukkan penggunaan API. Untuk informasi selengkapnya tentang kontrol akses, lihat Mengakses Cloud KMS API.

Gunakan metode cryptoKeyVersions.import untuk mengimpor kunci.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions:import" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"importJob": "IMPORT_JOB_ID", "algorithm": "ALGORITHM", "wrappedKey": "WRAPPED_KEY"}'

Ganti kode berikut:

  • IMPORT_JOB_ID: nama resource lengkap dari tugas impor yang sesuai.

  • ALGORITHM: algorithm kunci yang diimpor, yang berjenis CryptoKeyVersionAlgorithm.

  • WRAPPED_KEY: kunci yang digabungkan secara manual dalam format base64.

Permintaan impor kunci dimulai. Anda dapat memantau statusnya.

Memeriksa status versi kunci yang diimpor

Status awal untuk versi kunci yang diimpor adalah PENDING_IMPORT. Jika statusnya adalah ENABLED, berarti versi kunci telah berhasil diimpor. Jika impor gagal, statusnya adalah IMPORT_FAILED.

Anda dapat memeriksa status permintaan impor menggunakan Google Cloud CLI, Konsol Google Cloud, atau Cloud Key Management Service API.

Konsol

  1. Buka halaman Key Management di Konsol Google Cloud.

  2. Klik nama key ring yang berisi tugas impor Anda.

  3. Klik tab Impor Tugas di bagian atas halaman.

  4. Status akan terlihat di bagian Status di samping nama tugas impor Anda.

gcloud

Untuk menggunakan Cloud KMS di command line, Instal atau upgrade Google Cloud CLI ke versi terbaru terlebih dahulu.

Gunakan perintah versions list untuk memeriksa status. Gunakan lokasi, key ring target, dan kunci target yang sama dengan yang Anda buat sebelumnya dalam topik ini.

gcloud kms keys versions list \
  --keyring KEY_RING \
  --location LOCATION \
  --key KEY_NAME

Go

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu lalu instal Cloud KMS Go SDK.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// checkStateImportedKey checks the state of a CryptoKeyVersion in KMS.
func checkStateImportedKey(w io.Writer, name string) error {
	// name := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/cryptoKeys/my-imported-key/cryptoKeyVersions/1"

	// 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()

	// Call the API.
	result, err := client.GetCryptoKeyVersion(ctx, &kmspb.GetCryptoKeyVersionRequest{
		Name: name,
	})
	if err != nil {
		return fmt.Errorf("failed to get crypto key version: %w", err)
	}
	fmt.Fprintf(w, "Current state of crypto key version %q: %s\n", result.Name, result.State)
	return nil
}

Java

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Java SDK Cloud KMS.

import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class CheckStateImportedKey {

  public void checkStateImportedKey() 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 cryptoKeyId = "my-crypto-key";
    String cryptoKeyVersionId = "1";
    checkStateImportedKey(projectId, locationId, keyRingId, cryptoKeyId, cryptoKeyVersionId);
  }

  // Check the state of an imported key in Cloud KMS.
  public void checkStateImportedKey(
      String projectId,
      String locationId,
      String keyRingId,
      String cryptoKeyId,
      String cryptoKeyVersionId)
      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 version name from its path components.
      CryptoKeyVersionName versionName =
          CryptoKeyVersionName.of(
              projectId, locationId, keyRingId, cryptoKeyId, cryptoKeyVersionId);

      // Retrieve the state of an existing version.
      CryptoKeyVersion version = client.getCryptoKeyVersion(versionName);
      System.out.printf(
          "Current state of crypto key version %s: %s%n", version.getName(), version.getState());
    }
  }
}

Node.js

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu, lalu instal Node.js SDK Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const cryptoKeyId = 'my-imported-key';
// const cryptoKeyVersionId = '1';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key version name
const keyVersionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  cryptoKeyId,
  cryptoKeyVersionId
);

async function checkStateCryptoKeyVersion() {
  const [keyVersion] = await client.getCryptoKeyVersion({
    name: keyVersionName,
  });

  console.log(
    `Current state of key version ${keyVersion.name}: ${keyVersion.state}`
  );
  return keyVersion;
}

return checkStateCryptoKeyVersion();

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu lalu instal Cloud KMS Python SDK.

from google.cloud import kms

def check_state_imported_key(
    project_id: str, location_id: str, key_ring_id: str, import_job_id: str
) -> None:
    """
    Check the state of an import job 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').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified import_job string.
    import_job_name = client.import_job_path(
        project_id, location_id, key_ring_id, import_job_id
    )

    # Retrieve the state from an existing import job.
    import_job = client.get_import_job(name=import_job_name)

    print(f"Current state of import job {import_job.name}: {import_job.state}")

API

Contoh ini menggunakan curl sebagai klien HTTP untuk menunjukkan penggunaan API. Untuk informasi selengkapnya tentang kontrol akses, lihat Mengakses Cloud KMS API.

Panggil metode ImportJob.get dan periksa kolom state. Jika state adalah PENDING_GENERATION, tugas impor masih dibuat. Periksa kembali status secara berkala hingga menjadi ACTIVE.

Setelah versi kunci awal diimpor, status kunci akan berubah menjadi Aktif. Untuk kunci simetris, Anda harus menetapkan versi kunci yang diimpor sebagai versi utama sebelum dapat menggunakan kunci tersebut.

Kunci simetris: Menetapkan versi utama

Langkah ini diperlukan saat mengimpor kunci simetris, dan tidak relevan untuk kunci asimetris. Kunci asimetris tidak memiliki versi utama. Anda harus menggunakan Google Cloud CLI untuk menetapkan versi utama.

gcloud kms keys set-primary-version KEY_NAME\
    --location=LOCATION\
    --keyring=KEY_RING\
    --version=KEY_VERSION

Mengimpor ulang kunci yang sebelumnya dihancurkan

Cloud Key Management Service mendukung impor ulang kunci, yang memungkinkan Anda memulihkan versi kunci yang sebelumnya diimpor dalam status DESTROYED atau IMPORT_FAILED ke status ENABLED dengan menyediakan materi kunci asli. Jika belum ada materi kunci asli yang diimpor karena kegagalan impor awal, bahan kunci apa pun dapat disediakan.

Pembatasan

  • Hanya CryptoKeyVersions yang telah diimpor sebelumnya yang dapat diimpor ulang.
  • Materi kunci yang diimpor ulang harus sama persis dengan materi kunci asli jika versinya berhasil diimpor sebelumnya.
  • CryptoKeyVersions yang dihancurkan sebelum perilisan fitur ini tidak dapat diimpor ulang. Kolom reimport_eligible dari CryptoKeyVersion adalah true jika versi memenuhi syarat untuk diimpor ulang dan false jika tidak.

Kunci Software dan Cloud HSM dapat diimpor ulang, tetapi kunci eksternal tidak dapat diimpor ulang.

Mengimpor ulang kunci yang dihancurkan

Buat ImportJob untuk diimpor ulang dengan mengikuti langkah-langkah dalam Membuat tugas impor. Anda dapat menggunakan ImportJob yang ada atau ImportJob baru, selama tingkat perlindungannya cocok dengan tingkat perlindungan asli.

Konsol

  1. Buka halaman Key Management di konsol Google Cloud.

    Buka halaman Key Management

  2. Klik nama key ring yang berisi kunci yang versi kuncinya akan Anda impor ulang.

  3. Klik kunci yang versi kuncinya ingin Anda impor ulang.

  4. Klik tiga titik di samping versi kunci yang ingin Anda impor ulang.

  5. Pilih Impor ulang versi kunci

  6. Pilih tugas impor dari menu dropdown Pilih tugas impor.

  7. Di pemilih Upload the wrapped key, pilih kunci yang telah Anda gabung. Kunci ini harus cocok dengan materi kunci asli.

  8. Klik Re-Import.

gcloud

Untuk menggunakan Cloud KMS di command line, Instal atau upgrade Google Cloud CLI ke versi terbaru terlebih dahulu.

  1. Impor ulang versi kunci menggunakan materi kunci asli.

    gcloud kms keys versions import \
    --location LOCATION \
    --keyring KEY_RING \
    --key KEY_NAME \
    --version KEY_VERSION \
    --algorithm ALGORITHM \
    --import-job IMPORT_JOB \
    --target-key-file PATH_TO_KEY \
    

API

Contoh ini menggunakan curl sebagai klien HTTP untuk menunjukkan penggunaan API. Untuk informasi selengkapnya tentang kontrol akses, lihat Mengakses Cloud KMS API.

  1. Dalam isi permintaan metode cryptoKeyVersions.import, tetapkan kolom cryptoKeyVersion ke nama versi kunci dari versi yang diimpor. Ini harus berupa turunan dari kunci kripto.

  2. Dalam isi permintaan, tetapkan kolom algorithm ke algoritma kunci yang diimpor. Nilai ini harus sesuai dengan algoritma versi kunci asli. Kolom algorithm berjenis CryptoKeyVersionAlgorithm.

  3. Dalam isi permintaan, tetapkan kolom wrappedKeyMaterial ke materi kunci yang telah Anda gabungkan.

  4. Panggil metode cryptoKeyVersions.import. Respons cryptoKeyVersions.import adalah jenis CryptoKeyVersion. Setelah kunci berhasil diimpor, statusnya adalah ENABLED dan Anda dapat menggunakannya di Cloud KMS.

Langkah selanjutnya