Créer une clé

Cette page explique comment créer une clé dans Cloud KMS. Il peut s'agir d'une clé de chiffrement symétrique ou asymétrique, d'une clé de signature asymétrique ou d'une clé de signature MAC.

Lorsque vous créez une clé, vous l'ajoutez à un trousseau de clés situé dans un emplacement Cloud KMS spécifique. Vous pouvez créer un trousseau de clés ou en utiliser un existant. Sur cette page, vous allez générer une nouvelle clé Cloud KMS ou Cloud HSM et l'ajouter à un trousseau existant. Pour créer une clé Cloud EKM, consultez la section Créer une clé externe. Pour importer une clé Cloud KMS ou Cloud HSM, consultez la section Importer une clé.

Avant de commencer

Avant d'effectuer les tâches indiquées sur cette page, assurez-vous de disposer des éléments suivants:

  • Une ressource de projet Google Cloud pour stocker vos ressources Cloud KMS. Nous vous recommandons d'utiliser un projet distinct pour vos ressources Cloud KMS, qui ne contient aucune autre ressource Google Cloud.
  • Nom et emplacement du trousseau de clés dans lequel vous souhaitez créer votre clé. Choisissez un trousseau de clés situé à proximité de vos autres ressources et compatible avec le niveau de protection souhaité. Pour afficher les emplacements disponibles et les niveaux de protection qu'ils acceptent, consultez la page Emplacements Cloud KMS. Pour créer un trousseau de clés, consultez la page Créer un trousseau de clés.
  • Facultatif: Pour utiliser la gcloud CLI, préparez votre environnement.

    gcloud CLI

    Dans la console Google Cloud, activez Cloud Shell.

    Activer Cloud Shell

Rôles requis

Afin d'obtenir les autorisations nécessaires pour créer des clés, demandez à votre administrateur de vous attribuer le rôle IAM Administrateur Cloud KMS (roles/cloudkms.admin) sur le projet ou une ressource parente. Pour en savoir plus sur l'attribution de rôles, consultez la section Gérer les accès.

Ce rôle prédéfini contient les autorisations requises pour créer des clés. Pour connaître les autorisations exactes requises, développez la section Autorisations requises :

Autorisations requises

Les autorisations suivantes sont requises pour créer des clés:

  • 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
  • Pour récupérer une clé publique : cloudkms.cryptoKeyVersions.viewPublicKey

Vous pouvez également obtenir ces autorisations avec des rôles personnalisés ou d'autres rôles prédéfinis.

Créer une clé de chiffrement symétrique

Console

  1. Dans la console Google Cloud, accédez à la page Gestion des clés.

    Accéder à Key Management

  2. Cliquez sur le nom du trousseau de clés pour lequel vous souhaitez créer une clé.

  3. Cliquez sur Créer une clé.

  4. Pour Nom de la clé, saisissez le nom de votre clé.

  5. Pour Niveau de protection, sélectionnez Logiciel ou HSM.

  6. Dans Key material (Matériel de la clé), sélectionnez Generated key (Clé générée).

  7. Sous Purpose (Objectif), sélectionnez Symmetric encrypt/decrypt.

  8. Acceptez les valeurs par défaut pour Rotation period (Période de rotation) et Starting on (Rotation à partir du).

  9. Cliquez sur Créer.

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de Google Cloud CLI.

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

Remplacez les éléments suivants :

  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • PROTECTION_LEVEL: niveau de protection à utiliser pour la clé, par exemple software ou hsm. Vous pouvez omettre l'option --protection-level pour les clés software.

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C#, puis installez le SDK Cloud KMS pour C#.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Cloud KMS pour Node.js.

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

Pour exécuter ce code, commencez par en apprendre plus sur l'utilisation de PHP sur Google Cloud, puis installez le SDK Cloud KMS pour PHP.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby, puis installez le SDK Cloud KMS pour Ruby.

# 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

Ces exemples utilisent curl comme client HTTP pour démontrer l'utilisation de l'API. Pour en savoir plus sur le contrôle des accès, consultez la page Accéder à l'API Cloud KMS.

Pour créer une clé, utilisez la méthode 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" }}'

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet contenant le trousseau de clés.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • KEY_NAME : nom de la clé.
  • PROTECTION_LEVEL: niveau de protection de la clé (par exemple, SOFTWARE ou HSM).
  • ALGORITHM: algorithme de signature HMAC (par exemple, HMAC_SHA256). Pour afficher tous les algorithmes HMAC compatibles, consultez la section Algorithmes de signature HMAC.

Créer une clé de chiffrement symétrique avec rotation automatique personnalisée

Lorsque vous créez une clé, vous pouvez spécifier sa période de rotation, qui correspond au délai entre la création automatique de versions de clé. Vous pouvez également spécifier indépendamment la date de la prochaine rotation, afin que celle-ci ait lieu avant ou après la période de rotation à compter d'aujourd'hui.

Console

Lorsque vous utilisez la console Google Cloud pour créer une clé, Cloud KMS définit automatiquement la période de rotation et l'heure de la prochaine rotation. Vous pouvez choisir d'utiliser les valeurs par défaut ou de spécifier des valeurs différentes.

Pour spécifier une période de rotation et une date de début différentes, effectuez la procédure suivante lorsque vous créez votre clé, mais avant de cliquer sur le bouton Créer:

  1. Dans le champ Période de rotation des clés, sélectionnez une option.

  2. Pour À partir du, sélectionnez la date à laquelle vous souhaitez que la première rotation automatique ait lieu. Vous pouvez conserver la valeur par défaut du champ À partir du pour démarrer la première rotation automatique d'une période de rotation des clés à partir du moment où vous créez la clé.

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de 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

Remplacez les éléments suivants :

  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • ROTATION_PERIOD: intervalle de rotation de la clé (par exemple, 30d pour effectuer une rotation de la clé tous les 30 jours). La période de rotation doit être d'au moins un jour et de 100 ans au maximum. Pour en savoir plus, consultez la section CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: code temporel correspondant au moment où effectuer la première rotation (par exemple, "2023-01-01T01:02:03"). Vous pouvez omettre --next-rotation-time pour planifier la première rotation pendant sept jours à compter de la date d'exécution de la commande. Pour en savoir plus, consultez la section CryptoKey.nextRotationTime.

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C#, puis installez le SDK Cloud KMS pour C#.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Cloud KMS pour Node.js.

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

Pour exécuter ce code, commencez par en apprendre plus sur l'utilisation de PHP sur Google Cloud, puis installez le SDK Cloud KMS pour PHP.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby, puis installez le SDK Cloud KMS pour Ruby.

# 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

Ces exemples utilisent curl comme client HTTP pour démontrer l'utilisation de l'API. Pour en savoir plus sur le contrôle des accès, consultez la page Accéder à l'API Cloud KMS.

Pour créer une clé, utilisez la méthode 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"}'

Remplacez les éléments suivants :

  • PURPOSE: objectif de la clé.
  • ROTATION_PERIOD: intervalle de rotation de la clé (par exemple, 30d pour effectuer une rotation de la clé tous les 30 jours). La période de rotation doit être d'au moins un jour et de 100 ans au maximum. Pour en savoir plus, consultez la section CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: code temporel correspondant au moment où effectuer la première rotation (par exemple, "2023-01-01T01:02:03"). Vous pouvez omettre --next-rotation-time pour planifier la première rotation pendant sept jours à compter de la date d'exécution de la commande. Pour en savoir plus, consultez la section CryptoKey.nextRotationTime.

Définir la durée de l'état "Destruction programmée"

Par défaut, les versions de clé dans Cloud KMS passent 24 heures dans l'état de destruction programmée (DESTROY_SCHEDULED) avant d'être détruites. L'état de destruction programmée est parfois appelé état de suppression réversible. Vous pouvez configurer la durée de conservation des versions de clé dans cet état, avec les contraintes suivantes:

  • Vous ne pouvez définir la durée que lors de la création de la clé.
  • Une fois que la durée de la clé a été spécifiée, elle ne peut plus être modifiée.
  • La durée s'applique à toutes les versions de la clé créées par la suite.
  • La durée minimale est de 24 heures pour toutes les clés, à l'exception des clés d'importation uniquement, dont la durée minimale est de 0.
  • La durée maximale est de 120 jours.
  • La durée par défaut est de 24 heures.

Votre organisation peut avoir une valeur minimale de durée de destruction programmée définie par les règles d'administration. Pour en savoir plus, consultez la section Contrôler la destruction des clés.

Pour créer une clé qui utilise une durée personnalisée pour l'état Destruction programmée, procédez comme suit:

Console

  1. Dans la console Google Cloud, accédez à la page Gestion des clés.

    Accéder à Key Management

  2. Cliquez sur le nom du trousseau de clés pour lequel vous souhaitez créer une clé.

  3. Cliquez sur Créer une clé.

  4. Configurez les paramètres de la clé pour votre application.

  5. Cliquez sur Paramètres supplémentaires.

  6. Dans Durée de l'état "Destruction programmée", choisissez le nombre de jours pendant lesquels la destruction programmée sera maintenue avant d'être définitivement détruite.

  7. Cliquez sur Créer une clé.

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de Google Cloud CLI.

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

Remplacez les éléments suivants :

  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • PURPOSE: objectif de la clé (par exemple, encryption).
  • DURATION: durée pendant laquelle la clé reste à l'état Destruction programmée avant d'être détruite définitivement.

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

Nous vous recommandons d'utiliser la durée par défaut de 24 heures pour toutes les clés, sauf si vous avez des exigences réglementaires ou d'application spécifiques qui exigent une valeur différente.

Créer une clé asymétrique

Créer une clé de déchiffrement asymétrique

Suivez ces étapes pour créer une clé de déchiffrement asymétrique sur le trousseau de clés et l'emplacement spécifiés. Ces exemples peuvent être adaptés pour spécifier un niveau de protection ou un algorithme différent. Pour en savoir plus et connaître les autres valeurs, consultez Algorithmes et Niveaux de protection.

Lorsque vous créez la clé pour la première fois, l'état de la version initiale de la clé indique Génération en attente. Lorsque l'état passe à Activé, vous pouvez utiliser la clé. Pour en savoir plus sur les états des versions de clé, consultez États des versions de clé.

Console

  1. Dans la console Google Cloud, accédez à la page Gestion des clés.

    Accéder à Key Management

  2. Cliquez sur le nom du trousseau de clés pour lequel vous souhaitez créer une clé.

  3. Cliquez sur Créer une clé.

  4. Pour Nom de la clé, saisissez le nom de votre clé.

  5. Pour Niveau de protection, sélectionnez Logiciel ou HSM.

  6. Dans Key material (Matériel de la clé), sélectionnez Generated key (Clé générée).

  7. Dans le champ Objectif, sélectionnez Déchiffrement asymétrique.

  8. Dans le champ Algorithme, sélectionnez RSA 3 072 bits - Padding OAEP - Digest. Vous pouvez modifier cette valeur sur les futures versions de clé.

  9. Cliquez sur Créer.

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de Google Cloud CLI.

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

Remplacez les éléments suivants :

  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • ALGORITHM: algorithme à utiliser pour la clé (par exemple, rsa-decrypt-oaep-3072-sha256). Pour obtenir la liste des algorithmes de chiffrement asymétrique compatibles, consultez la page Algorithmes de chiffrement asymétrique.

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C#, puis installez le SDK Cloud KMS pour C#.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Cloud KMS pour Node.js.

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

Pour exécuter ce code, commencez par en apprendre plus sur l'utilisation de PHP sur Google Cloud, puis installez le SDK Cloud KMS pour PHP.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby, puis installez le SDK Cloud KMS pour Ruby.

# 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

Ces exemples utilisent curl comme client HTTP pour démontrer l'utilisation de l'API. Pour en savoir plus sur le contrôle des accès, consultez la page Accéder à l'API Cloud KMS.

Créez une clé de déchiffrement asymétrique en appelant 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"}}'

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet contenant le trousseau de clés.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • KEY_NAME : nom de la clé.
  • ALGORITHM: algorithme à utiliser pour la clé (par exemple, RSA_DECRYPT_OAEP_3072_SHA256). Pour obtenir la liste des algorithmes de chiffrement asymétrique compatibles, consultez la page Algorithmes de chiffrement asymétrique.

Créer une clé de signature asymétrique

Suivez ces étapes pour créer une clé de signature asymétrique sur le trousseau de clés et l'emplacement spécifiés. Ces exemples peuvent être adaptés pour spécifier un niveau de protection ou un algorithme différent. Pour en savoir plus et connaître les autres valeurs, consultez Algorithmes et Niveaux de protection.

Lorsque vous créez la clé pour la première fois, l'état de la version initiale de la clé indique Génération en attente. Lorsque l'état passe à Activé, vous pouvez utiliser la clé. Pour en savoir plus sur les états des versions de clé, consultez États des versions de clé.

Console

  1. Dans la console Google Cloud, accédez à la page Gestion des clés.

    Accéder à Key Management

  2. Cliquez sur le nom du trousseau de clés pour lequel vous souhaitez créer une clé.

  3. Cliquez sur Créer une clé.

  4. Pour Nom de la clé, saisissez le nom de votre clé.

  5. Pour Niveau de protection, sélectionnez Logiciel ou HSM.

  6. Dans Key material (Matériel de la clé), sélectionnez Generated key (Clé générée).

  7. Dans le champ Objectif, sélectionnez Signature asymétrique.

  8. Dans le champ Algorithme, sélectionnez Elliptic Curve P-256 - SHA256 Digest (Courbe elliptique P-256 – Condensé SHA256). Vous pouvez modifier cette valeur dans les futures versions de clé.

  9. Cliquez sur Créer.

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de Google Cloud CLI.

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

Remplacez les éléments suivants :

  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • ALGORITHM: algorithme à utiliser pour la clé (par exemple, ec-sign-p256-sha256). Pour obtenir la liste des algorithmes compatibles, consultez la page Algorithmes de signature asymétrique.

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C#, puis installez le SDK Cloud KMS pour C#.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Cloud KMS pour Node.js.

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

Pour exécuter ce code, commencez par en apprendre plus sur l'utilisation de PHP sur Google Cloud, puis installez le SDK Cloud KMS pour PHP.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby, puis installez le SDK Cloud KMS pour Ruby.

# 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

Ces exemples utilisent curl comme client HTTP pour démontrer l'utilisation de l'API. Pour en savoir plus sur le contrôle des accès, consultez la page Accéder à l'API Cloud KMS.

Créez une clé de signature asymétrique en appelant 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"}}'

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet contenant le trousseau de clés.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • KEY_NAME : nom de la clé.
  • ALGORITHM: algorithme à utiliser pour la clé (par exemple, EC_SIGN_P256_SHA256). Pour obtenir la liste des algorithmes compatibles, consultez la page Algorithmes de signature asymétrique.

Récupérer la clé publique

Lorsque vous créez une clé asymétrique, Cloud KMS crée une paire de clés publique/privée. Une fois la clé générée, vous pouvez récupérer la clé publique d'une clé asymétrique activée à tout moment.

La clé publique est au format PEM (Privacy-enhanced Electronic Mail). Pour en savoir plus, consultez les sections de la RFC 7468 sur la page General Items (Remarques générales) et Textual Encoding of Subject Public Key Info (Encodage textuel des informations sur la clé publique de l'objet).

Pour télécharger la clé publique d'une version de clé asymétrique existante, procédez comme suit:

Console

  1. Dans la console Google Cloud, accédez à la page Gestion des clés.

    Accéder à Key Management

  2. Cliquez sur le nom du trousseau de clés contenant la clé asymétrique pour laquelle vous souhaitez récupérer la clé publique.

  3. Cliquez sur le nom de la clé pour laquelle vous souhaitez récupérer la clé publique.

  4. Sur la ligne correspondant à la version de clé pour laquelle vous souhaitez récupérer la clé publique, cliquez sur View more (Afficher plus) .

  5. Cliquez sur Get the public key (Obtenir la clé publique).

  6. La clé publique s'affiche dans l'invite. Vous pouvez copier la clé publique dans votre presse-papiers. Pour télécharger la clé publique, cliquez sur Download (Télécharger).

Si l'option Obtenir la clé publique ne s'affiche pas, vérifiez les éléments suivants:

  • La clé est une clé asymétrique.
  • La version de clé est activée.
  • Vous disposez de l'autorisation cloudkms.cryptoKeyVersions.viewPublicKey.

Le nom de fichier d'une clé publique téléchargée à partir de la console Google Cloud se présente sous la forme suivante:

KEY_RING-KEY_NAME-KEY_VERSION.pub

Chaque partie du nom de fichier est séparée par un trait d'union, par exemple ringname-keyname-version.pub

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de Google Cloud CLI.

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

Remplacez les éléments suivants :

  • KEY_VERSION: numéro de version de la clé.
  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • OUTPUT_FILE_PATH: chemin d'accès où vous souhaitez enregistrer le fichier de clé publique (par exemple, public-key.pub).

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C#, puis installez le SDK Cloud KMS pour C#.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Cloud KMS pour Node.js.

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

Pour exécuter ce code, commencez par en apprendre plus sur l'utilisation de PHP sur Google Cloud, puis installez le SDK Cloud KMS pour PHP.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby, puis installez le SDK Cloud KMS pour Ruby.

# 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

Ces exemples utilisent curl comme client HTTP pour démontrer l'utilisation de l'API. Pour en savoir plus sur le contrôle des accès, consultez la page Accéder à l'API Cloud KMS.

Récupérez la clé publique en appelant la méthode CryptoKeyVersions.getPublicKey.

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

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet contenant le trousseau de clés.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • KEY_NAME : nom de la clé.
  • KEY_VERSION: numéro de version de la clé.

Le résultat doit ressembler à ce qui suit :

{
  "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": "SOFTWARE"
}

Convertir une clé publique au format JWK

Cloud KMS vous permet de récupérer une clé publique au format PEM. Certaines applications peuvent nécessiter d'autres formats de clé, tels que la clé Web JSON (JWK). Pour en savoir plus sur le format JWK, consultez le document RFC 7517.

Pour convertir une clé publique au format JWK, procédez comme suit:

Go

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.

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)

Contrôler l'accès aux clés asymétriques

Un signataire ou un validateur doit disposer de l'autorisation ou du rôle approprié sur la clé asymétrique.

  • Pour un utilisateur ou un service qui effectue la signature, accordez l'autorisation cloudkms.cryptoKeyVersions.useToSign sur la clé asymétrique.

  • Pour un utilisateur ou un service qui récupère la clé publique, accordez l'autorisation cloudkms.cryptoKeyVersions.viewPublicKey sur la clé asymétrique. La clé publique est nécessaire à la validation de la signature.

Pour en savoir plus sur les autorisations et les rôles dans la version de Cloud KMS, consultez la page Autorisations et rôles.

Créer une clé de signature MAC

Console

  1. Dans la console Google Cloud, accédez à la page Gestion des clés.

    Accéder à Key Management

  2. Cliquez sur le nom du trousseau de clés pour lequel vous souhaitez créer une clé.

  3. Cliquez sur Créer une clé.

  4. Pour Nom de la clé, saisissez le nom de votre clé.

  5. Pour le champ Niveau de protection, sélectionnez Logiciel ou HSM.

  6. Dans Key material (Matériel de la clé), sélectionnez Generated key (Clé générée).

  7. Dans le champ Objectif, sélectionnez Signature/validation MAC.

  8. Facultatif: Dans le champ Algorithme, sélectionnez un algorithme de signature HMAC.

  9. Cliquez sur Créer.

gcloud

Pour utiliser Cloud KMS sur la ligne de commande, commencez par installer la dernière version de Google Cloud CLI ou passer à la dernière version de Google Cloud CLI.

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

Remplacez les éléments suivants :

  • KEY_NAME : nom de la clé.
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • ALGORITHM: algorithme de signature HMAC (par exemple, hmac-sha256). Pour afficher tous les algorithmes HMAC compatibles, consultez la section Algorithmes de signature HMAC.
  • PROTECTION_LEVEL: niveau de protection de la clé (par exemple, hsm). Vous pouvez omettre l'option --protection-level pour les clés software.

Pour en savoir plus sur toutes les options et valeurs possibles, exécutez la commande avec l'option --help.

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C#, puis installez le SDK Cloud KMS pour C#.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Go, puis installez le SDK Cloud KMS pour Go.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Cloud KMS pour Java.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Cloud KMS pour Node.js.

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

Pour exécuter ce code, commencez par en apprendre plus sur l'utilisation de PHP sur Google Cloud, puis installez le SDK Cloud KMS pour PHP.

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

Pour exécuter ce code, commencez par configurer un environnement de développement Python, puis installez le SDK Cloud KMS pour Python.


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

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby, puis installez le SDK Cloud KMS pour Ruby.

# 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

Ces exemples utilisent curl comme client HTTP pour démontrer l'utilisation de l'API. Pour en savoir plus sur le contrôle des accès, consultez la page Accéder à l'API Cloud KMS.

Pour créer une clé, utilisez la méthode 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" }}'

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet contenant le trousseau de clés.
  • LOCATION: emplacement Cloud KMS du trousseau de clés ;
  • KEY_RING: nom du trousseau de clés contenant la clé.
  • KEY_NAME : nom de la clé.
  • PROTECTION_LEVEL: niveau de protection de la clé, par exemple SOFTWARE ou HSM.
  • ALGORITHM: algorithme de signature HMAC, par exemple HMAC_SHA256. Pour afficher tous les algorithmes HMAC compatibles, consultez la section Algorithmes de signature HMAC.

Étapes suivantes