Como criar chaves simétricas

O Cloud Key Management Service usa uma hierarquia de objetos que reside em um local específico. Nessa hierarquia, uma chave pertence a um keyring.

Criar um keyring

O keyring é definido pelos respectivos local e nome.

Console

  1. Acesse a página Chaves criptográficas no console do GCP.
    Acessar a página "Chaves criptográficas".

  2. Clique em Criar keyring.

  3. No campo Nome do keyring, digite o nome do seu keyring.

  4. No menu suspenso Local, selecione um local.
    A página Criar keyring terá esta aparência:

    Criar uma chave

  5. Clique em Criar

Linha de comando

Crie um novo keyring com o nome [KEYRING_NAME] no local [LOCATION].

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

C#

      public static void CreateKeyRing(string projectId, string locationId, string keyRingId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The location in which to create the key ring.
          LocationName locationName = new LocationName(projectId, locationId);

          // Initial values for the KeyRing (currently unused).
          KeyRing keyRing = new KeyRing();

          KeyRing result = client.CreateKeyRing(locationName, keyRingId, keyRing);
          Console.Write($"Created Key Ring: {result.Name}");
      }

Go


// createKeyRing creates a new ring to store keys on KMS.
// example parentName: "projects/PROJECT_ID/locations/global/"
func createKeyRing(w io.Writer, parentName, keyRingID string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}
	// Build the request.
	req := &kmspb.CreateKeyRingRequest{
		Parent:    parentName,
		KeyRingId: keyRingID,
	}
	// Call the API.
	result, err := client.CreateKeyRing(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Created key ring: %s", result)
	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.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // The resource name of the location associated with the KeyRing.
    String parent = LocationName.format(projectId, locationId);

    // Create the KeyRing for your project.
    KeyRing keyRing = client.createKeyRing(parent, keyRingId, KeyRing.newBuilder().build());

    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

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\KeyRing;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';

$kms = new KeyManagementServiceClient();

// The resource name of the KeyRing.
$locationName = $kms->locationName($projectId, $locationId);

$keyRing = new KeyRing();

// Create the CryptoKey for your project.
$newKeyRing = $kms->createKeyRing(
    $locationName,
    $keyRingId,
    $keyRing
);

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)."""

    from google.cloud import kms_v1

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the location associated with the KeyRing.
    parent = client.location_path(project_id, location_id)

    # The keyring object template
    keyring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    keyring = {'name': keyring_name}

    # Create a KeyRing
    response = client.create_key_ring(parent, key_ring_id, keyring)

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

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/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The location associated with the key ring
location = CloudKMS::KeyManagementServiceClient.location_path project_id, location_id

# KeyRing creation parameters (currently unused)
key_ring_spec = CloudKMS::KeyRing.new

# Create a key ring for your project
key_ring = client.create_key_ring location, key_ring_id, key_ring_spec

puts "Created key ring #{key_ring_id}"

Criar uma chave

Você precisa criar a chave em um keyring.

Console

  1. Acesse a página Chaves criptográficas no console do GCP.
    Acessar a página "Chaves criptográficas".

  2. Clique no nome do keyring em que a chave será criada.

  3. Clique em Criar chave.

  4. No campo Nome da chave, insira o nome da sua chave.

  5. Aceite os valores padrão de Período de rotação e A partir de. Se quiser usar valores diferentes, defina um período de rotação de chaves e o horário de início.

  6. [Opcional] No campo Rótulos, clique em Adicionar rótulo para adicioná-los à chave.
    A página Criar chave terá esta aparência:

    Criar uma chave

  7. Clique em Criar

Linha de comando

Crie uma nova chave [KEY_NAME] para o keyring [KEYRING_NAME].

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

C#

      public static void CreateCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
      {
          KeyManagementServiceClient client = KeyManagementServiceClient.Create();

          // The KeyRing in which to create the CryptoKey.
          KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

          CryptoKey cryptoKeyToCreate = new CryptoKey();
          cryptoKeyToCreate.Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt;

          CryptoKey result = client.CreateCryptoKey(keyRingName, cryptoKeyId, cryptoKeyToCreate);
          Console.Write($"Created Crypto Key: {result.Name}");
      }

Go


// createCryptoKey creates a new symmetric encrypt/decrypt key on KMS.
// example keyRingName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID"
func createCryptoKey(w io.Writer, keyRingName, keyID string) error {
	ctx := context.Background()
	client, err := cloudkms.NewKeyManagementClient(ctx)
	if err != nil {
		return err
	}

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      keyRingName,
		CryptoKeyId: keyID,
		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 err
	}
	fmt.Fprintf(w, "Created crypto key. %s", result)
	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.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // The resource name of the location associated with the KeyRing.
    String parent = KeyRingName.format(projectId, locationId, keyRingId);

    // This will allow the API access to the key for encryption and decryption.
    CryptoKey cryptoKey = CryptoKey.newBuilder()
        .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
        .build();

    // Create the CryptoKey for your project.
    CryptoKey createdKey = client.createCryptoKey(parent, cryptoKeyId, cryptoKey);

    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

use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The location ID of the crypto key. Can be "global", "us-west1", etc.';
// $keyRingId = 'The KMS key ring ID';
// $cryptoKeyId = 'The KMS key ID';

$kms = new KeyManagementServiceClient();

// The resource name of the KeyRing.
$keyRingName = $kms->keyRingName($projectId, $locationId, $keyRingId);

$cryptoKey = new CryptoKey();
// This will allow the API access to the key for encryption and decryption.
$cryptoKey->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT);

// Create the CryptoKey for your project.
$newKey = $kms->createCryptoKey(
    $keyRingName,
    $cryptoKeyId,
    $cryptoKey
);

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."""

    from google.cloud import kms_v1
    from google.cloud.kms_v1 import enums

    # Creates an API client for the KMS API.
    client = kms_v1.KeyManagementServiceClient()

    # The resource name of the KeyRing associated with the CryptoKey.
    parent = client.key_ring_path(project_id, location_id, key_ring_id)

    # Create the CryptoKey object template
    purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    crypto_key = {'purpose': purpose}

    # Create a CryptoKey for the given KeyRing.
    response = client.create_crypto_key(parent, crypto_key_id, crypto_key)

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

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/cloud/kms/v1"
CloudKMS = Google::Cloud::Kms::V1

# Initialize the client
client = CloudKMS::KeyManagementServiceClient.new

# The key ring to use
key_ring =
  CloudKMS::KeyManagementServiceClient.key_ring_path project_id, location_id, key_ring_id

# CryptoKey creation parameters
crypto_key_spec = CloudKMS::CryptoKey.new
crypto_key_spec.purpose = CloudKMS::CryptoKey::CryptoKeyPurpose::ENCRYPT_DECRYPT

# Create a crypto key in the key ring
crypto_key = client.create_crypto_key key_ring, crypto_key_id, crypto_key_spec

puts "Created crypto key #{crypto_key_id}"

Configurar um período de rotação e horário de início para a chave

É possível criar uma chave com um período de rotação especificado, que é o período entre a geração automática de novas versões de chave. A chave também pode ser criada com um próximo tempo de rotação.

Console

Ao utilizar o Console do Google Cloud Platform para criar uma chave, caso você não especifique seu próprio período de rotação e o período seguinte, eles serão automaticamente configurados pelo Cloud KMS.

Para especificar um período de rotação e um horário de início diferentes, siga as etapas abaixo quando estiver criando a chave, antes de clicar no botão Criar:

  1. clique no menu suspenso Período de rotação e selecione um valor para o período;
  2. no campo Iniciar em, clique na data e selecione uma para a próxima rotação.

Linha de comando

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]

Criar manualmente novas versões de chave

Além da rotação automática, é possível fazer a rotação manual das chaves. Para mais detalhes, consulte Como fazer rotação de chaves.

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…