Creazione e convalida delle firme digitali MAC

Questo argomento fornisce informazioni sulla creazione e sulla convalida delle firme digitali basate sulle chiavi MAC.

Un'unica chiave, condivisa sia dal producer che dal verificatore, viene utilizzata per calcolare un tag MAC dai dati di input. Il tag MAC funge da firma digitale. Quando il verificatore riceve il messaggio e il tag MAC associato, genera il proprio tag dai contenuti del messaggio. Il verificatore può quindi confrontare il tag ricevuto con quello generato per vedere se corrispondono. Se i due tag corrispondono, il verificatore sa che il messaggio ricevuto è uguale a quello firmato dal producer.

Prima di iniziare

  • Quando crei firme digitali MAC, devi utilizzare una chiave con lo scopo chiave di MAC. Quando crei la chiave, utilizza MAC.

  • Assicurati che le dimensioni del file che vuoi firmare non superino i limiti di dimensione. Quando utilizzi una chiave Cloud HSM per creare o verificare le firme MAC, la dimensione massima del file è 16 KiB. Per tutte le altre chiavi, la dimensione massima del file è 64 KiB.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per creare e verificare le firme, chiedi all'amministratore di concederti i seguenti ruoli IAM sulla chiave:

Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso.

Potresti anche essere in grado di ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

Creazione di una firma MAC

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima installare o eseguire l'upgrade alla versione più recente di Google Cloud CLI.

gcloud kms mac-sign \
    --version KEY_VERSION \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --input-file INPUT_FILE_PATH \
    --signature-file SIGNED_FILE_PATH

Sostituisci quanto segue:

  • KEY_VERSION: il numero di versione della chiave.
  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • INPUT_FILE_PATH: il percorso locale del file che vuoi firmare.
  • SIGNED_FILE_PATH: il percorso locale in cui vuoi salvare la firma generata.

Per informazioni su tutti i flag e i possibili valori, esegui il comando con il flag --help.

C#

Per eseguire questo codice, prima configura un ambiente di sviluppo C# e installa l'SDK C# di Cloud KMS.


using Google.Cloud.Kms.V1;
using Google.Protobuf;

public class SignMacSample
{
    public byte[] SignMac(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
      string data = "Sample data")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Convert the data into a ByteString.
        ByteString dataByteString = ByteString.CopyFromUtf8(data);

        // Call the API.
        MacSignResponse result = client.MacSign(keyVersionName, dataByteString);

        // The data comes back as raw bytes, which may include non-printable
        // characters. To print the result, you could encode it as base64.
        // string encodedSignature = result.Mac.ToBase64();

        // Get the signature.
        byte[] signature = result.Mac.ToByteArray();

        // Return the result.
        return signature;
    }
}

Go

Per eseguire questo codice, prima configura un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"

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

// signMac will sign a plaintext message using the HMAC algorithm.
func signMac(w io.Writer, name string, data string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"
	// data := "my data to sign"

	// 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.MacSignRequest{
		Name: name,
		Data: []byte(data),
	}

	// Generate HMAC of data.
	result, err := client.MacSign(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to hmac sign: %w", err)
	}

	// The data comes back as raw bytes, which may include non-printable
	// characters. This base64-encodes the result so it can be printed below.
	encodedSignature := base64.StdEncoding.EncodeToString(result.Mac)

	fmt.Fprintf(w, "Signature: %s", encodedSignature)
	return nil
}

Java

Per eseguire questo codice, prima configura un ambiente di sviluppo Java e installa l'SDK Java di Cloud KMS.

import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.MacSignResponse;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.Base64;

public class SignMac {

  public void signMac() 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 keyId = "my-key";
    String keyVersionId = "123";
    String data = "Data to sign";
    signMac(projectId, locationId, keyRingId, keyId, keyVersionId, data);
  }

  // Sign data with a given mac key.
  public void signMac(
      String projectId,
      String locationId,
      String keyRingId,
      String keyId,
      String keyVersionId,
      String data)
      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 key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Generate an HMAC of the data.
      MacSignResponse response = client.macSign(keyVersionName, ByteString.copyFromUtf8(data));

      // The data comes back as raw bytes, which may include non-printable
      // characters. This base64-encodes the result so it can be printed below.
      String encodedSignature = Base64.getEncoder().encodeToString(response.getMac().toByteArray());
      System.out.printf("Signature: %s%n", encodedSignature);
    }
  }
}

Node.js

Per eseguire questo codice, prima configura un ambiente di sviluppo Node.js e installa l'SDK Node.js di Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'your-project-id';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';
// const data = Buffer.from('...');

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

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

// Build the version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function signMac() {
  // Sign the data with Cloud KMS
  const [signResponse] = await client.macSign({
    name: versionName,
    data: data,
  });

  // Example of how to display signature. Because the signature is in a binary
  // format, you need to encode the output before printing it to a console or
  // displaying it on a screen.
  const encoded = signResponse.mac.toString('base64');
  console.log(`Signature: ${encoded}`);

  return signResponse;
}

return signMac();

Python

Per eseguire questo codice, prima configura un ambiente di sviluppo Python e installa l'SDK Python di Cloud KMS.

from google.cloud import kms

def sign_mac(
    project_id: str,
    location_id: str,
    key_ring_id: str,
    key_id: str,
    version_id: str,
    data: str,
) -> kms.MacSignResponse:
    """
    Sign a message using the private key part of 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): Version to use (e.g. '1').
        data (string): Data to sign.

    Returns:
        MacSignResponse: Signature.
    """

    # Import base64 for printing the ciphertext.
    import base64

    # 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
    )

    # Convert the message to bytes.
    data_bytes = data.encode("utf-8")

    # Call the API
    sign_response = client.mac_sign(
        request={"name": key_version_name, "data": data_bytes}
    )

    print(f"Signature: {base64.b64encode(sign_response.mac)!r}")
    return sign_response

Ruby

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Ruby e poi installare l'SDK Ruby di Cloud KMS.

# 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"
# data        = "my data"

# Require the library.
require "google/cloud/kms"

# Require digest.
require "digest"

# 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.
sign_response = client.mac_sign name: key_version_name, data: data

# The data comes back as raw bytes, which may include non-printable
# characters. This base64-encodes the result so it can be printed below.
encoded_signature = Base64.strict_encode64 sign_response.mac

puts "Signature: #{encoded_signature}"

API

In questi esempi viene utilizzato curl come client HTTP per dimostrare l'utilizzo dell'API. Per maggiori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

Utilizza il metodo CryptoKeyVersions.macSign per eseguire la firma. La risposta da questo metodo contiene la firma con codifica Base64.

Verifica di una firma MAC

gcloud

Per utilizzare Cloud KMS nella riga di comando, devi prima installare o eseguire l'upgrade alla versione più recente di Google Cloud CLI.

gcloud kms mac-verify \
    --version KEY_VERSION \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --input-file INPUT_FILE_PATH \
    --signature-file SIGNED_FILE_PATH
  • KEY_VERSION: il numero di versione della chiave.
  • KEY_NAME: il nome della chiave.
  • KEY_RING: il nome del keyring che contiene la chiave.
  • LOCATION: la località Cloud KMS del keyring.
  • INPUT_FILE_PATH: il percorso locale del file firmato.
  • SIGNED_FILE_PATH: il percorso locale del file della firma da verificare.

Per informazioni su tutti i flag e i possibili valori, esegui il comando con il flag --help.

C#

Per eseguire questo codice, prima configura un ambiente di sviluppo C# e installa l'SDK C# di Cloud KMS.


using Google.Cloud.Kms.V1;
using Google.Protobuf;

public class VerifyMacSample
{
    public bool VerifyMac(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
      string data = "my data",
      byte[] signature = null)
    {
        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Convert the data and signatures into ByteStrings.
        ByteString dataByteString = ByteString.CopyFromUtf8(data);
        ByteString signatureByteString = ByteString.CopyFrom(signature);

        // Verify the signature.
        MacVerifyResponse result = client.MacVerify(keyVersionName, dataByteString, signatureByteString);

        // Return the result.
        return result.Success;
    }
}

Go

Per eseguire questo codice, prima configura un ambiente di sviluppo Go e installa l'SDK Cloud KMS Go.

import (
	"context"
	"fmt"
	"io"

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

// verifyMac will verify a previous HMAC signature.
func verifyMac(w io.Writer, name string, data, signature []byte) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"
	// data := "my previous data"
	// signature := []byte("...")  // Response from a sign request

	// 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.MacVerifyRequest{
		Name: name,
		Data: data,
		Mac:  signature,
	}

	// Verify the signature.
	result, err := client.MacVerify(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to verify signature: %w", err)
	}

	fmt.Fprintf(w, "Verified: %t", result.Success)
	return nil
}

Java

Per eseguire questo codice, prima configura un ambiente di sviluppo Java e installa l'SDK Java di Cloud KMS.

import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.MacVerifyResponse;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class VerifyMac {

  public void verifyMac() 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 keyId = "my-key";
    String keyVersionId = "123";
    String data = "Data to sign";
    byte[] signature = null;
    verifyMac(projectId, locationId, keyRingId, keyId, keyVersionId, data, signature);
  }

  // Sign data with a given mac key.
  public void verifyMac(
      String projectId,
      String locationId,
      String keyRingId,
      String keyId,
      String keyVersionId,
      String data,
      byte[] signature)
      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 key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyVersionName keyVersionName =
          CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

      // Verify the signature
      MacVerifyResponse response =
          client.macVerify(
              keyVersionName, ByteString.copyFromUtf8(data), ByteString.copyFrom(signature));

      // The data comes back as raw bytes, which may include non-printable
      // characters. This base64-encodes the result so it can be printed below.
      System.out.printf("Success: %s%n", response.getSuccess());
    }
  }
}

Node.js

Per eseguire questo codice, prima configura un ambiente di sviluppo Node.js e installa l'SDK Node.js di Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'your-project-id';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';
// const data = Buffer.from('...');
// const signature = Buffer.from('...');

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

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

// Build the version name
const versionName = client.cryptoKeyVersionPath(
  projectId,
  locationId,
  keyRingId,
  keyId,
  versionId
);

async function verifyMac() {
  // Verify the data with Cloud KMS
  const [verifyResponse] = await client.macVerify({
    name: versionName,
    data: data,
    mac: signature,
  });

  console.log(`Verified: ${verifyResponse.success}`);
  return verifyResponse;
}

return verifyMac();

Python

Per eseguire questo codice, prima configura un ambiente di sviluppo Python e installa l'SDK Python di Cloud KMS.

from google.cloud import kms

def verify_mac(
    project_id: str,
    location_id: str,
    key_ring_id: str,
    key_id: str,
    version_id: str,
    data: str,
    signature: bytes,
) -> kms.MacVerifyResponse:
    """
    Verify the signature of data from an HMAC 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): Version to use (e.g. '1').
        data (string): Data that was signed.
        signature (bytes): Signature bytes.

    Returns:
        MacVerifyResponse: Success.
    """

    # 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
    )

    # Convert the message to bytes.
    data_bytes = data.encode("utf-8")

    # Call the API
    verify_response = client.mac_verify(
        request={"name": key_version_name, "data": data_bytes, "mac": signature}
    )

    print(f"Verified: {verify_response.success}")
    return verify_response

Ruby

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Ruby e poi installare l'SDK Ruby di Cloud KMS.

# 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"
# data        = "my data"
# signature   = "..."

# Require the library.
require "google/cloud/kms"

# Require digest.
require "digest"

# 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.
verify_response = client.mac_verify name: key_version_name, data: data, mac: signature
puts "Verified: #{verify_response.success}"

API

In questi esempi viene utilizzato curl come client HTTP per dimostrare l'utilizzo dell'API. Per maggiori informazioni sul controllo dell'accesso, consulta Accesso all'API Cloud KMS.

Utilizza il metodo CryptoKeyVersions.macVerify per eseguire la verifica. La firma da verificare deve essere codificata in Base64. La risposta di questo metodo contiene un valore booleano che indica se la firma è stata verificata correttamente o meno.