Crear claves simétricas

Cloud Key Management Service usa una jerarquía de objetos, como una clave que pertenece a un llavero de claves, que reside en una ubicación particular.

Crea un llavero de claves

Un llavero de claves se define por su ubicación y nombre.

Console

  1. Ve a la página Claves criptográficas de GCP Console.
    Ir a la página Claves criptográficas

  2. Haz clic en Crear llavero de claves.

  3. En el campo Nombre del llavero de claves, ingresa el nombre de tu llavero de claves.

  4. Desde el menú desplegable Ubicación, selecciona una ubicación.
    Tu página Crear llavero de claves debe ser similar a la siguiente:

    Crea una clave

  5. Haz clic en Crear.

Línea de comandos

Crea un llavero de claves nuevo con el nombre [KEYRING_NAME] en la ubicación [LOCATION].

gcloud kms keyrings create [KEYRING_NAME] --location [LOCATION]

C#

      public static object CreateKeyRing(string projectId, string locationId, string keyRingId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for creating key rings.
          var parent = $"projects/{projectId}/locations/{locationId}";
          KeyRing keyRingToCreate = new KeyRing();
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CreateRequest(
              cloudKms, keyRingToCreate, parent);
          request.KeyRingId = keyRingId;
          var result = request.Execute();
          Console.Write($"Created Key Ring: {result.Name}");
          return 0;
      }

Go

func createKeyring(project, keyRing string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s", project, location)

	_, err = client.Projects.Locations.KeyRings.Create(
		parent, &cloudkms.KeyRing{}).KeyRingId(keyRing).Do()
	if err != nil {
		return err
	}
	log.Print("Created key ring.")

	return nil
}

Java

/**
 * Creates a new key ring with the given id.
 */
public static KeyRing createKeyRing(String projectId, String locationId, String keyRingId)
    throws IOException {
  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the location associated with the KeyRing.
  String parent = String.format("projects/%s/locations/%s", projectId, locationId);
  // Create the KeyRing for your project.
  KeyRing keyring = kms.projects().locations().keyRings()
      .create(parent, new KeyRing())
      .setKeyRingId(keyRingId)
      .execute();

  System.out.println(keyring);
  return keyring;
}

Node.js

async function createKeyRing(
  projectId = 'YOUR_PROJECT_ID', // Your GCP projectId
  keyRingId = 'my-new-key-ring' // Name of the new key ring
) {
  // The location of the new key ring, e.g. "global"
  const locationId = 'global';

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // Get the full path to the parent
  const parent = client.locationPath(projectId, locationId);

  // Creates a new key ring
  const [result] = await client.createKeyRing({parent, keyRingId});
  console.log(`Key ring ${result.name} created.`);
}

PHP

/**
 * Create a KeyRing.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $locationId [optional]
 * @return null
 */
function create_keyring($projectId, $keyRingId, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the location associated with the KeyRing.
    $parent = sprintf('projects/%s/locations/%s',
        $projectId,
        $locationId
    );

    // Create the KeyRing for your project.
    $keyRing = new Google_Service_CloudKMS_KeyRing();
    $kms->projects_locations_keyRings->create(
        $parent,
        $keyRing,
        ['keyRingId' => $keyRingId]
    );

    printf('Created keyRing %s' . PHP_EOL, $keyRingId);
}

Python

def create_key_ring(project_id, location_id, key_ring_id):
    """Creates a KeyRing in the given location (e.g. global)."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the location associated with the KeyRing.
    parent = 'projects/{}/locations/{}'.format(project_id, location_id)

    # Create KeyRing
    request = kms_client.projects().locations().keyRings().create(
        parent=parent, body={}, keyRingId=key_ring_id)
    response = request.execute()

    print('Created KeyRing {}.'.format(response['name']))

Ruby

# project_id  = "Your Google Cloud project ID"
# key_ring_id = "The ID of the new key ring"
# location_id = "The location of the new key ring"

require "google/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the key ring
resource = "projects/#{project_id}/locations/#{location_id}"

# Create a key ring for your project
key_ring = kms_client.create_project_location_key_ring(
  resource,
  Cloudkms::KeyRing.new,
  key_ring_id: key_ring_id
)

puts "Created key ring #{key_ring_id}"

Crea una clave

Se debe crear una clave en un llavero de claves.

Console

  1. Ve a la página Claves criptográficas de GCP Console.
    Ir a la página Claves criptográficas

  2. Haz clic en el nombre del llavero de claves para el cual crearás una clave.

  3. Haz clic en Crear clave.

  4. Ingresa el nombre en el campo Nombre de la clave.

  5. Acepta los valores predeterminados de Período de rotación y A partir del, o define un período de rotación de clave y tiempo de inicio si quieres usar valores diferentes.

  6. [Opcional] En el campo Etiquetas, haz clic en Agregar etiqueta si quieres agregar etiquetas a tu clave.
    Tu página Crear clave debe ser similar a la siguiente:

    Crea una clave

  7. Haz clic en Crear.

Línea de comandos

Crea una clave nueva [KEY_NAME] para el llavero de claves [KEYRING_NAME].

gcloud kms keys create [KEY_NAME] --location [LOCATION] \
  --keyring [KEYRING_NAME] --purpose encryption

C#

      public static object CreateCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for creating the crypto key.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}";
          CryptoKey cryptoKeyToCreate = new CryptoKey();
          cryptoKeyToCreate.Purpose = "ENCRYPT_DECRYPT";
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource.CreateRequest(
              cloudKms, cryptoKeyToCreate, parent);
          request.CryptoKeyId = cryptoKeyId;
          var result = request.Execute();
          Console.Write($"Created Crypto Key: {result.Name}");
          return 0;
      }

Go

func createCryptoKey(project, keyRing, key string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s", project, location, keyRing)
	purpose := "ENCRYPT_DECRYPT"

	_, err = client.Projects.Locations.KeyRings.CryptoKeys.Create(
		parent, &cloudkms.CryptoKey{
			Purpose: purpose,
		}).CryptoKeyId(key).Do()
	if err != nil {
		return err
	}
	log.Print("Created crypto key.")

	return nil
}

Java

/**
 * Creates a new crypto key with the given id.
 */
public static CryptoKey createCryptoKey(String projectId, String locationId, String keyRingId,
    String cryptoKeyId)
    throws IOException {
  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the location associated with the KeyRing.
  String parent = String.format(
      "projects/%s/locations/%s/keyRings/%s", projectId, locationId, keyRingId);

  // This will allow the API access to the key for encryption and decryption.
  String purpose = "ENCRYPT_DECRYPT";
  CryptoKey cryptoKey = new CryptoKey();
  cryptoKey.setPurpose(purpose);

  // Create the CryptoKey for your project.
  CryptoKey createdKey = kms.projects().locations().keyRings().cryptoKeys()
      .create(parent, cryptoKey)
      .setCryptoKeyId(cryptoKeyId)
      .execute();

  System.out.println(createdKey);
  return createdKey;
}

Node.js

async function createCryptoKey(
  projectId = 'your-project-id', // Your GCP Project Id
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key' // Name of the crypto key
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the new crypto key's key ring, e.g. "global"
  const locationId = 'global';

  const parent = client.keyRingPath(projectId, locationId, keyRingId);

  // Creates a new key ring
  const [cryptoKey] = await client.createCryptoKey({
    parent,
    cryptoKeyId,
    cryptoKey: {
      // This will allow the API access to the key for encryption and decryption
      purpose: 'ENCRYPT_DECRYPT',
    },
  });
  console.log(`Key ${cryptoKey.name} created.`);
}

PHP

/**
 * Create a CryptoKey.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $locationId [optional]
 * @return Google_Service_CloudKMS_CryptoKey
 */
function create_cryptokey($projectId, $keyRingId, $cryptoKeyId, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // This will allow the API access to the key for encryption and decryption.
    $purpose = 'ENCRYPT_DECRYPT';

    // The resource name of the KeyRing associated with the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s',
        $projectId,
        $locationId,
        $keyRingId
    );

    $cryptoKey = new Google_Service_CloudKMS_CryptoKey();
    $cryptoKey->setPurpose($purpose);

    // Create the CryptoKey for your project.
    $newKey = $kms->projects_locations_keyRings_cryptoKeys->create(
        $parent,
        $cryptoKey,
        ['cryptoKeyId' => $cryptoKeyId]
    );

    printf('Created cryptoKey %s in keyRing %s' . PHP_EOL, $cryptoKeyId, $keyRingId);
}

Python

def create_crypto_key(project_id, location_id, key_ring_id, crypto_key_id):
    """Creates a CryptoKey within a KeyRing in the given location."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the KeyRing associated with the CryptoKey.
    parent = 'projects/{}/locations/{}/keyRings/{}'.format(
        project_id, location_id, key_ring_id)

    # Create a CryptoKey for the given KeyRing.
    request = kms_client.projects().locations().keyRings().cryptoKeys().create(
        parent=parent, body={'purpose': 'ENCRYPT_DECRYPT'},
        cryptoKeyId=crypto_key_id)
    response = request.execute()

    print('Created CryptoKey {}.'.format(response['name']))

Ruby

# project_id    = "Your Google Cloud project ID"
# location_id   = "The location of the key ring"
# key_ring_id   = "The ID of the key ring"
# crypto_key_id = "The ID of the new crypto key"

require "google/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the key ring
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}"

# Create a crypto key in the key ring
new_crypto_key = kms_client.create_project_location_key_ring_crypto_key(
  resource,
  Cloudkms::CryptoKey.new(purpose: "ENCRYPT_DECRYPT"),
  crypto_key_id: crypto_key_id
)

puts "Created crypto key #{crypto_key_id}"

Define un período de rotación de clave y tiempo de inicio

Se puede crear una clave con un período de rotación específico, que es el tiempo que transcurre entre la generación automática de versiones de claves nuevas. También se puede crear una clave con un período de rotación siguiente específico.

Console

Cuando usas Google Cloud Platform Console para crear una clave, si no especificas tus propios período de rotación y siguiente período de rotación, Cloud KMS los definirá de manera automática.

Para especificar un período de rotación y tiempo de inicio diferentes, cuando estás creando tu clave, pero antes de hacer clic en el botón Crear, sigue estos pasos:

  1. Haz clic en el menú desplegable Período de rotación y, luego, selecciona un valor para el período.
  2. Haz clic en la fecha en el campo A partir del y, luego, selecciona una fecha para la siguiente rotación.

Línea de comandos

gcloud kms keys create [KEY_NAME] --location [LOCATION] \
  --keyring [KEYRING_NAME] \
  --purpose encryption \
  --rotation-period [ROTATION_PERIOD] \
  --next-rotation-time [NEXT_ROTATION_TIME]

Windows cmd.exe

gcloud kms keys create [KEY_NAME] --location [LOCATION] ^
  --keyring [KEYRING_NAME] ^
  --purpose encryption  ^
  --rotation-period [ROTATION_PERIOD] ^
  --next-rotation-time [NEXT_ROTATION_TIME]

PowerShell

gcloud kms keys create [KEY_NAME] --location [LOCATION] `
  --keyring [KEYRING_NAME] `
  --purpose encryption `
  --rotation-period [ROTATION_PERIOD] `
  --next-rotation-time [NEXT_ROTATION_TIME]

Crea versiones de claves nuevas de forma manual

Además de la rotación automática, puedes rotar la claves de forma manual. Para obtener más detalles, consulta Rotación de claves.

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

Documentación de Cloud KMS